0% found this document useful (0 votes)
21 views114 pages

Unit 3

Uploaded by

nehal.arora
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views114 pages

Unit 3

Uploaded by

nehal.arora
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 114

Unit-3

Linked List
Concept of List

⚫ List:
⚫ A list is an ordered data structure with elements
separated by a comma and enclosed within
square brackets.
⚫ Linked List:
⚫ Linked List is a linear data structure.
⚫ All elements are stored at contiguous memory
location
⚫ Link list data structure is dynamic in nature
⚫ Linked List can be defined as collection of objects
called nodes that are randomly stored in the
memory.
⚫ Memory will be allocated at run time i.e. while
running program
Linked List
⚫ Linked List is a linear data structure.
⚫ All elements are stored at contiguous
memory location
⚫ Link list data structure is dynamic in
nature
⚫ Memory will be allocated at run time
i.e.while running program
Linked List
⚫ Linked List can be defined as collection of objects
called nodes that are randomly stored in the
memory.
⚫ A node contains two fields i.e. data stored at that
particular address and the pointer which contains
the address of the next node in the memory.
⚫ The last node of the list contains pointer to the
null.
Why Linked List?
⚫ Arrays can be used to store linear data of
similar types, but arrays have the following
limitations:
⚫ 1. The size of the arrays is fixed.
⚫ 2.Insertion of a new element / Deletion of a
existing element in an array of elements is
expensive: The room has to be created for the
new elements and to create room existing
elements have to be shifted ,
but in Linked list if we have the head node
then we can traverse to any node through it
and insert new node at the required position.
Difference in Array and Link List
Advantages of Linked Lists over arrays:

⚫ Dynamic Array.
⚫ Ease of Insertion/Deletion.
⚫ Types of Linked Lists:
⚫ Simple Linked List
⚫ Doubly Linked List
⚫ Circular Linked List
C malloc()

⚫ The name "malloc" stands for memory allocation.


⚫ The malloc() function reserves a block of memory
of the specified number of bytes. And, it returns
a pointer of void which can be casted into pointers
of any form.
⚫ The “malloc” or “memory allocation” method in
C is used to dynamically allocate a single large
block of memory with the specified size. It returns
a pointer of type void which can be cast into a
pointer of any form. It doesn’t Initialize memory
at execution time so that it has initialized each
block with the default garbage value initially.
⚫ malloc() is used to dynamically allocate a single
block of memory in C, it is available in the header
file stdlib.h.
Dynamic memory allocation
⚫ malloc
⚫ Syntax: ptr = (cast-type*) malloc(byte-size)
⚫ ptr = (struct node *) malloc(sizeof(struct node *));
//Link list have dynamic size.malloc allocates memory in
run time
⚫ For Example:
⚫ ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will
allocate 400 bytes of memory. And, the pointer
ptr holds the address of the first byte in the
allocated memory.
Comparison in Sequential and linked
organization
⚫ Comparison in sequential and linked
organization
Types of Linked Lists:

⚫ Simple Linked List – In this type of linked


list, one can move or traverse the linked list
in only one direction
⚫ Doubly Linked List – In this type of linked
list, one can move or traverse the linked list
in both directions (Forward and Backward)
⚫ Circular Linked List – In this type of linked
list, the last node of the linked list contains
the link of the first/head node of the linked
list in its next pointer and the first/head node
contains the link of the last node of the
linked list in its prev pointer
single linked list
⚫ In any single linked list, the individual element is
called as "Node". Every "Node" contains two fields,
data field, and the next field. The data field is used to
store actual value of the node and next field is used
to store the address of next node in the sequence.
The graphical representation of a node in a single
linked list is as follows...

⚫ Important Points to be Remembered


In a single linked list, the address of the first node is always
Operations on Single Linked List
⚫ The following operations are performed on a
Single Linked List
⚫ Create a node
⚫ Insertion:
1.Inserting at the beginning of the list
2. Inserting at the end of the list
3. Inserting at specific location in the list
⚫ Deletion:
1.Deleting from beginning of the list
2. Deleting from end of the list
3.Deleting a specific node
⚫ Display
Creating a Node:
⚫ Let's define a data type of struct LinkedList .
⚫ The first step of creating linked list of n nodes starts from
defining node structure. We need a custom type to store our
data and location of next linked node. Let us define our
custom node structure
⚫ struct node
⚫ {
⚫ int data; //actual value
⚫ struct node *next; //next means next part of the node and
*means pointer, which indicates that next part we have to
store the address.
⚫ };
⚫ Where data is the data you want to store in list. *next is pointer to
the same structure type. The *next will store location of next node
if exists otherwise NULL.
Insertion
⚫ In a single linked list, the insertion
operation can be performed in three ways.
They are as follows...
⚫ Inserting At Beginning of the list
⚫ Inserting At End of the list
⚫ Inserting At Specific location in the list
1.Inserting At Beginning of the list
⚫ We can use the following steps to insert a new node at
beginning of the single linked list...
⚫ Step 1 - Create a newNode with given value.
⚫ Step 2 - Check whether list is Empty (head == NULL)
⚫ Step 3 - If it is Empty then,
set newNode→next = NULL and head = newNode.
⚫ Step 4 - If it is Not Empty then,
set newNode→next = head and head = newNode.
2.Inserting At End of the list
⚫ We can use the following steps to insert a new node at end of
the single linked list...
⚫ Step 1 - Create a newNode with given value and newNode →
next as NULL.
⚫ Step 2 - Check whether list is Empty (head == NULL).
⚫ Step 3 - If it is Empty then, set head = newNode.
⚫ Step 4 - If it is Not Empty then, define a node
pointer temp and initialize with head.
⚫ Step 5 - Keep moving the temp to its next node until it
reaches to the last node in the list (until temp → next is equal
to NULL).
⚫ Step 6 - Set temp → next = newNode.
3.Inserting At Specific location in the list (After a Node)
Step 1 - Create a newNode with given value.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty then, set newNode →
next = NULL and head = newNode.
Step 4 - If it is Not Empty then, define a node pointer temp and
initialize with head.
Step 5 - Keep moving the temp to its next node until it reaches to
the node after which we want to insert the newNode (until temp1
→ data is equal to location, here location is the node value after
which we want to insert the newNode).
Step 6 - Every time check whether temp is reached to last node or
not. If it is reached to last node then display 'Given node is not
found in the list and terminate the function. Otherwise move
the temp(17) to next node.
Step 7 - Finally, Set 'newNode → next = temp → next' and
'temp → next = newNode'
Deletion
⚫ In a single linked list, the deletion
operation can be performed in three ways.
They are as follows...
⚫ Deleting from Beginning of the list
⚫ Deleting from End of the list
⚫ Deleting a Specific Node
Deleting from Beginning of the list
⚫ Step 1 - Check whether list is Empty (head == NULL)
⚫ Step 2 - If it is Empty then, display 'List is Empty!!! Deletion
is not possible' and terminate the function.
⚫ Step 3 - If it is Not Empty then, define a Node
pointer 'temp' and initialize with head.
⚫ Step 4 - Check whether list is having only one node (temp →
next == NULL)
⚫ Step 5 - If it is TRUE then set head = NULL and
delete temp (Setting Empty list conditions)
⚫ Step 6 - If it is FALSE then set head = temp → next, and
delete temp.
Deleting from End of the list
⚫ Step 1 - Check whether list is Empty (head == NULL)
⚫ Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminate the function.
⚫ Step 3 - If it is Not Empty then, define two Node
pointers 'temp1' and 'temp2' and initialize 'temp1' with head.
⚫ Step 4 - Check whether list has only one Node (temp1 →
next == NULL)
⚫ Step 5 - If it is TRUE. Then, set head = NULL and
delete temp1. And terminate the function. (Setting Empty list
condition)
⚫ Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and
move temp1 to its next node. Repeat the same until it reaches
to the last node in the list. (until temp1 → next == NULL)
⚫ Step 7 - Finally, Set temp2 → next = NULL and delete temp1.
Deleting a Specific Node from the list:Singly link list
⚫ Step 1 - Check whether list
is Empty (head == NULL)
⚫ Step 2 - If it is Empty then, display 'List is Empty!!!
Deletion is not possible' and terminate the function.
⚫ Step 3 - If it is Not Empty then, define two Node
pointers 'temp1' and 'temp2' and initialize 'temp1'
with head.
⚫ Step 4 - Keep moving the temp1 until it reaches to
the exact node to be deleted or to the last node. And
every time set 'temp2 = temp1' before moving the
'temp1' to its next node.
⚫ Step 5 - If it is reached to the last node then
display 'Given node not found in the list! Deletion
not possible!!!'. And terminate the function.
⚫ Step 6 - If it is reached to the exact node which we
want to delete, then check whether list is having only
Deleting a Specific Node from the list:Singly link list
⚫ Step 8 - If list contains multiple nodes, then check whether temp1 is
the first node in the list (temp1 == head).
⚫ Step 9 - If temp1 is the first node then move the head to the next
node (head = head → next) and delete temp1//temp1=93.
⚫ Step 10 - If temp1 is not first node then check whether it is last node
in the list (temp1 → next == NULL).
⚫ Step 11 - If temp1 is last node then set temp2 → next = NULL and
delete temp1 (free(temp1)).//temp2=17
⚫ Step 12 - If temp1 is not first node and not last node then set temp2
→ next = temp1 → next and delete temp1 (free(temp1)).
Displaying a Single Linked List
⚫ We can use the following steps to display the elements of a
single linked list...
⚫ Step 1 - Check whether list is Empty (head == NULL)
⚫ Step 2 - If it is Empty then, display 'List is Empty!!!' and
terminate the function.
⚫ Step 3 - If it is Not Empty then, define a Node
pointer 'temp' and initialize with head.
⚫ Step 4 - Keep displaying temp → data with an arrow (--->)
until temp reaches to the last node
⚫ Step 5 - Finally display temp → data with arrow pointing
to NULL (temp → data ---> NULL).
Types of Linked Lists:
⚫ Singly Linked List
⚫ It is the most common. Each node has data
and a pointer to the next node.

⚫ Node is represented as:


Singly Linked List
A three-member singly linked list can be created
as:
Doubly Linked List

⚫ We add a pointer to the previous node in a


doubly-linked list. Thus, we can go in either
direction: forward or backward.

⚫ A node is represented as
A three-member doubly linked list can be created as

A three member doubly linklist


Doubly Link List

Create list when there is no element present


Insertion
⚫ Inserting at the beginning of the list
Insertion
⚫ Inserting at end of the list
Insertion
⚫ Insert at specific location of list
Circular Linked List
⚫ A circular linked list is a variation of a linked
list in which the last element is linked to the
first element. This forms a circular loop.

⚫ A circular linked list can be either singly linked


or doubly linked.
⚫ for singly linked list, next pointer of last item
points to the first item
⚫ In the doubly linked list, prev pointer of the
first item points to the last item as well
A circular linked list

⚫ A three-member circular singly linked list can


be created as:
Simple Linked List
Singly linked list
⚫ In this type of linked list, one can move or
traverse the linked list in only one direction
⚫ Singly linked list can be defined as the
collection of ordered set of elements.
⚫ A node in the singly linked list consist of two
parts: data part and link part.
⚫ i.e.every node contains some data and a
pointer to the next node of the same data
type
Singly linked list
⚫ One way chain or singly linked list can be
traversed only in one direction. In other
words, we can say that each node contains
only next pointer, therefore we can not
traverse the list in the reverse direction.
Traversing In Singly Linked List
⚫ The process of visiting each node of the list
once to perform some operation on it is called
traversing. It is performed in almost every
scenario of the singly linked list
⚫ Algorithm:
⚫ STEP 1: SET PTR = HEAD
⚫ STEP 2:IF PTR = NULL
WRITE “LIST IS EMPTY”
GOTO STEP 7
END OF IF
⚫ STEP 4: REPEAT STEP 5 AND 6 UNTIL PTR
!= NULL
⚫ STEP 5: PRINT PTR→ DATA
⚫ STEP 6:PTR = PTR → NEXT
[END OF LOOP]
⚫ STEP 7: EXIT
Insertion in singly linked list at beginning
⚫ There are the following steps which need to be
followed in order to insert a new node in the list at
beginning.
⚫ Allocate the space for the new node and store
data into the data part of the node. This will be
done by the following statements.
⚫ ptr = (struct node *) malloc(sizeof(struct node *));
ptr → data = item
⚫ Make the link part of the new node pointing to
the existing first node of the list. This will be done
by using the following statement.
⚫ ptr->next = head;
⚫ At the last, we need to make the new node as the
first node of the list this will be done by using the
following statement.
Insertion at beginning of singly link list

⚫ Insertion in singly linked list at


beginning
Insertion in singly linked list at the end
⚫ The condition Head = NULL would fail, since Head is not null. Now,
we need to declare a temporary pointer temp in order to traverse
through the list. temp is made to point the first node of the list.
⚫ Temp = head
⚫ Then, traverse through the entire linked list using the statements:
⚫ while (temp→ next != NULL)
⚫ temp = temp → next;
At the end of the loop, the temp will be pointing to the last node of
the list. Now, allocate the space for the new node, and assign the item
to its data part.Since, the new node is going to be the last node of the
list hence, the next part of this node needs to be pointing to the null.
We need to make the next part of the temp node (which is currently
the last node of the list) point to the new node (ptr) .
⚫ temp = head;
⚫ while (temp -> next != NULL)
⚫ {
⚫ temp = temp -> next;
⚫ }
⚫ temp->next = ptr;
Insertion in singly linked list at the end
⚫ Insertion in singly linked list at the end
Deletion in singly linked list at the end
There are two scenarios in which, a node is deleted from the
end of the linked list.
⚫ There is only one node in the list and that needs to be
deleted.
⚫ There are more than one node in the list and the last node of
the list will be deleted.
⚫ In the first scenario,
⚫ the condition head → next = NULL will survive and
therefore, the only node head of the list will be assigned to
null. This will be done by using the following statements.
⚫ ptr = head
⚫ head = NULL
⚫ free(ptr)
⚫ In the second scenario,
⚫ The condition head → next = NULL would fail and therefore,
we have to traverse the node in order to reach the last node
of the list.
⚫ For this purpose,declare a temporary pointer temp and
assign it to head of the list. We also need to keep track of the
second last node of the list. For this purpose, two pointers ptr
and ptr1 will be used where ptr will point to the last node and
ptr1 will point to the second last node of the list.
Deletion in singly linked list at the end
⚫ ptr = head;
⚫ while(ptr->next != NULL)
⚫ {
⚫ ptr1 = ptr;
⚫ ptr = ptr ->next;
⚫ }
⚫ we just need to make the pointer ptr1 point to the NULL and
the last node of the list that is pointed by ptr will become
free. It will be done by using the following statements.
ptr1->next = NULL;
⚫ free(ptr);
Deletion in singly linked list at the end
⚫ Deletion in singly linked list at the end
Insertion
⚫ The insertion into a singly linked list can be performed at
different positions. Based on the position of the new node
being inserted, the insertion is categorized into the following
categories.
Deletion and Traversing in Singly link list
Doubly Linked List

⚫ In this type of linked list, one can move or


traverse the linked list in both directions
(Forward and Backward)
⚫ Doubly linked list is a complex type of linked
list in which a node contains a pointer to the
previous as well as the next node in the
sequence. Therefore, it contains three parts
are data, a pointer to the next node, and a
pointer to the previous node
⚫ i.e.DLL contains an extra pointer, typically
called previous pointer, together with the next
pointer and data which are there in the singly
linked list.
Doubly Linked List
⚫ Therefore, in a doubly linked list, a node
consists of three parts: node data, pointer to
the next node in sequence (next pointer) ,
pointer to the previous node (previous
pointer).

⚫ A doubly linked list containing three nodes


having numbers from 1 to 3 in their data part,
is shown in the following image.
Doubly linked list
Advantages over singly linked list
1) A DLL can be traversed in both forward and
backward directions.
2) The delete operation in DLL is more efficient if
a pointer to the node to be deleted is given.
3) We can quickly insert a new node before a
given node.
Disadvantages over singly linked list
1) Every node of DLL Requires extra space for a
previous pointer.
2) All operations require an extra pointer previous
to be maintained

Insertion
A node can be added in four ways
1) At the front of the DLL
2) After a given node.
Operations on doubly linked list
Doubly Linked List
⚫ A doubly linked list is a type of linked list in
which each node consists of 3 components:
⚫ *prev - address of the previous node
⚫ data - data item
⚫ *next - address of next node
Single node in doubly link list is represented as
⚫ struct node
⚫ {
⚫ int data;
⚫ struct node *next;
⚫ struct node *prev;
⚫ }
⚫ Each struct node has a data item, a pointer to
the previous struct node, and a pointer to the
next struct node.
Representation of Doubly Linked List

⚫ In the above code, one, two, and three are the


nodes with data items 1, 2, and 3 respectively.
⚫ For node one: next stores the address
of two and prev stores null (there is no node
before it)
⚫ For node two: next stores the address
of three and prev stores the address of one
⚫ For node three: next stores null (there is no
node after it) and prev stores the address
of two.
To create a simple doubly linked list with three items
⚫ /* Initialize nodes */
⚫ struct node *head;
⚫ struct node *one = NULL;
⚫ struct node *two = NULL;
⚫ struct node *three = NULL;
⚫ /* Allocate memory */
⚫ one = malloc(sizeof(struct node));
⚫ two = malloc(sizeof(struct node));
⚫ three = malloc(sizeof(struct node));
⚫ /* Assign data values */
⚫ one->data = 1;
⚫ two->data = 2;
⚫ three->data = 3;
⚫ /* Connect nodes */
⚫ one->next = two;
⚫ one->prev = NULL;
⚫ two->next = three;
⚫ two->prev = one;
⚫ three->next = NULL;
⚫ three->prev = two;
⚫ /* Save address of first node in head */
⚫ head = one;
Insertion on a Doubly Linked List
⚫ Pushing a node to a doubly-linked list is
similar to pushing a node to a linked list, but
extra work is required to handle the pointer to
the previous node.
⚫ We can insert elements at 3 different positions
of a doubly-linked list:
⚫ Insertion at the beginning
⚫ Insertion in-between nodes
⚫ Insertion at the End
⚫ Suppose we have a double-linked list with
elements 1, 2, and 3.
Inserting in a doubly linklist
⚫ 1. Insertion at the Beginning
⚫ Let's add a node with value 6 at the beginning
of the doubly linked list we made above.
⚫ 1. Create a new node
⚫ allocate memory for newNode
⚫ assign the data to newNode.
Inserting in a doubly linklist
⚫ 2.Set prev and next pointers of new node
⚫ point next of newNode to the first node of the
doubly linked list
⚫ point prev to null

⚫ 3. Make new node as head node


⚫ Point prev of the first node to newNode (now the
previous head is the second node)
⚫ Point head to newNode.
Code for Insertion at the Beginning
⚫ // insert node at the front
⚫ void insertFront(struct Node** head, int data) {
⚫ // allocate memory for newNode
⚫ struct Node* newNode = new Node;
⚫ // assign data to newNode
⚫ newNode->data = data;
⚫ // point next of newNode to the first node of the
doubly linked list
⚫ newNode->next = (*head);
⚫ // point prev to NULL
⚫ newNode->prev = NULL;
⚫ // point previous of the first node (now first node is
the second node) to newNode
⚫ if ((*head) != NULL)
⚫ (*head)->prev = newNode;
⚫ // head points to newNode
⚫ (*head) = newNode;
⚫ }
Doubly linklist

⚫ 2. Insertion in between two nodes:Let's add a


node with value 6 after node with value 1 in the
doubly linked list.
⚫ 1. Create a new node
⚫ allocate memory for newNode
⚫ assign the data to newNode.
⚫ 2. Set prev and next pointers of new node and the
previous node:If the linked list is empty, make
the newNode as the head node. Otherwise,
traverse to the end of the doubly linked list and
Doubly linklist

⚫ The final doubly linked list looks like this.


Code for Insertion at the End(doubly linklist)
⚫ void insertEnd(struct Node** head, int data) // insert a newNode at the end of the list {
⚫ struct Node* newNode = new Node; // allocate memory for node
⚫ // assign data to newNode
⚫ newNode->data = data;
⚫ // assign NULL to next of newNode
⚫ newNode->next = NULL;
⚫ // store the head node temporarily (for later use)
⚫ struct Node* temp = *head;
⚫ // if the linked list is empty, make the newNode as head node
⚫ if (*head == NULL) {
⚫ newNode->prev = NULL;
⚫ *head = newNode;
⚫ return;}
⚫ // if the linked list is not empty, traverse to the end of the linked list
⚫ while (temp->next != NULL)
⚫ temp = temp->next;
⚫ // now, the last node of the linked list is temp
⚫ // point the next of the last node (temp) to newNode.
⚫ temp->next = newNode;
⚫ // assign prev of newNode to temp
⚫ newNode->prev = temp;
⚫ }
Deletion from a Doubly Linked List
⚫ Similar to insertion, we can also delete a node
from 3 different positions of a doubly linked list.
⚫ Suppose we have a double-linked list with elements 1, 2,
and 3.

⚫ 1. Delete the First Node of Doubly Linked List: If the node to be


deleted (i.e. del_node) is at the beginning
⚫ Reset value node after the del_node (i.e. node two)

⚫ Finally, free the memory of del_node. And, the linked will look like
this
Code for Deletion of the First Node(doubly link list)
⚫ Code for Deletion of the First Node
Deletion of the Inner Node
⚫ 2. Deletion of the Inner Node
⚫ If del_node is an inner node (second node), we
must have to reset the value
of next and prev of the nodes before and after
the del_node.
⚫ For the node before the del_node (i.e. first
node)
⚫ Assign the value of next of del_node to
the next of the first node.
⚫ For the node after the del_node (i.e. third
node)
⚫ Assign the value of prev of del_node to
the prev of the third node.
Deletion of the Inner Node
⚫ Finally, we will free the memory of del_node.
And, the final doubly linked list looks like this.

⚫ Code for Deletion of the Inner Node


Delete the Last Node of Doubly Linked List
⚫ 3. Delete the Last Node of Doubly Linked List
⚫ In this case, we are deleting the last node with value 3 of the
doubly linked list.
⚫ Here, we can simply delete the del_node and make
the next of node before del_node point to NULL.

⚫ The final doubly linked list looks like this.

⚫ Code for Deletion of the Last Node: Here, del_node


->next is NULL so del_node->prev->next = NULL.
Doubly Linked List Code
Doubly link list code:
Singly Link list Vs Doubly Link list

Singly Link list Vs Doubly Link list


Circular Linked List
⚫ A circular linked list is a type of linked list in
which the first and the last nodes are also
connected to each other to form a circle.
⚫ There are basically two types of circular linked
list:
⚫ 1. Circular Singly Linked List
⚫ Here, the address of the last node consists of
the address of the first node.
Circular Doubly Linked List
⚫ Circular Doubly Linked List:Here, in addition to
the last node storing the address of the first node,
the first node will also store the address of the last
node.
Representation of Circular Linked List
⚫ Let's see how we can represent a circular linked
list on an code. Suppose we have a linked list:

⚫ Here, the single node is represented as

Each struct node has a data item and a pointer to the


next struct node.
create a simple circular linked list with three items
⚫ simple circular linked list: In the above code, one, two, and
three are the nodes with data items 1, 2, and 3 respectively.
Circular Linked List
⚫ For node one
⚫ next stores the address of two (there is no
node before it)
⚫ For node two
⚫ next stores the address of three
⚫ For node three
⚫ next stores NULL (there is no node after it)
⚫ next points to node one
Insertion on a Circular Linked List
⚫ We can insert elements at 3 different positions
of a circular linked list:
⚫ Insertion at the beginning
⚫ Insertion in-between nodes
⚫ Insertion at the end
⚫ Suppose we have a circular linked list with
elements 1, 2, and 3.
Circular Link List
⚫ Let's add a node with value 6 at different
positions of the circular linked list we made
above. The first step is to create a new node.
⚫ allocate memory for newNode
⚫ assign the data to newNode
1. Insertion at the Beginning (circular link list)

⚫ store the address of the current first node in


the newNode (i.e. pointing the newNode to the
current first node)
⚫ point the last node to newNode (i.e
making newNode as head)

Insert at the beginning


Circular Link List

⚫ 2. Insertion in between two nodes


⚫ Let's insert newNode after the first node.
⚫ travel to the node given (let this node be p)
⚫ point the next of newNode to the node next
to p
⚫ store the address of newNode at next of p
Circular Link List
⚫ 3. Insertion at the end
⚫ store the address of the head node to next of newNode
(making newNode the last node)
⚫ point the current last node to newNode
⚫ make newNode as the last node

⚫ Deletion on a Circular Linked List


⚫ Suppose we have a double-linked list with elements 1, 2, and
3.
Circular link list
⚫ 1. If the node to be deleted is the only node
⚫ free the memory occupied by the node
⚫ store NULL in last
⚫ 2. If last node is to be deleted
⚫ find the node before the last node (let it be temp)
⚫ store the address of the node next to the last node in temp
⚫ free the memory of last
⚫ make temp as the last node
⚫ 3. If any other nodes are to be deleted
⚫ travel to the node to be deleted (here we are deleting node 2)
⚫ let the node before node 2 be temp
⚫ store the address of the node next to 2 in temp
⚫ free the memory of 2
Circular Linked List Code
⚫ code
Circular Link List

.
Circular linked list
⚫ The circular linked list is a linked list where all
nodes are connected to form a circle.
⚫ In a circular linked list, the first node and the last
node are connected to each other which forms a
circle. There is no NULL at the end.
Circular Linked List
⚫ Circular singly linked list:
⚫ In a circular Singly linked list, the last node of
the list contains a pointer to the first node of
the list.
⚫ We traverse the circular singly linked list until
we reach the same node where we started.
⚫ The circular singly linked list has no
beginning or end. No null value is present in
the next part of any of the nodes.
Circular Linked List
⚫ Circular Doubly linked list: Circular Doubly
Linked List has properties of both doubly
linked list and circular linked list
⚫ In this two consecutive elements are linked or
connected by the previous and next pointer,
and the last node points to the first node by
the next pointer and also the first node points
to the last node by the previous pointer.
⚫ i.e. last node of the list contains the address of
the first node of the list. The first node of the
list also contain address of the last node in its
previous pointer.
Operations on circular doubly linked list

⚫ Operations on circular doubly linked list :


Applications of linked list in computer science –
⚫ Implementation of stacks and queue
⚫ Implementation of graphs : Adjacency list
representation of graphs is most popular
which uses linked list to store adjacent
vertices.
⚫ Maintaining directory of names
⚫ Performing arithmetic operations on long
integers
⚫ Manipulation of polynomials by storing
constants in the node of linked list
⚫ representing sparse matrices
⚫ Memory management
Abstract data type

⚫ Abstract Data Type(ADT) is a data type,


where only behavior is defined but not
implementation.
⚫ Examples:
Array, List, Map, Queue, Set, Stack, Table,
Tree, and Vector are ADTs
Abstract data type
⚫ Abstract data type model: Before knowing
about the abstract data type model, we should
know about abstraction and encapsulation.
⚫ Abstraction: It is a technique of hiding the
internal details from the user and only showing
the necessary details to the user.
⚫ Encapsulation: It is a technique of combining
the data and the member function in a single
unit is known as encapsulation.
ADT
⚫ The above figure shows the ADT model. There are
two types of models in the ADT model, i.e., the
public function and the private function. The
ADT model also contains the data structures that
we are using in a program.
⚫ In this model, first encapsulation is performed,
i.e., all the data is wrapped in a single unit, i.e.,
ADT.
⚫ Then, the abstraction is performed means
showing the operations that can be performed on
the data structure and what are the data structures
that we are using in a program.
ADT
⚫ Generally,ADTs are mathematical or logical
concepts that can be implemented on
different machines using different languages.
Furthermore, they’re very flexible and don’t
dependent on languages or machines.
ADT
.
ADT
ADT

.
ADT
.
Three ADTs are List ADT, Stack ADT, Queue ADT
⚫ List ADT
⚫ The data is generally stored in key sequence in a list
which has a head structure consisting
of count, pointers and address of compare
function needed to compare the data in the list.
⚫ The data node contains the pointer to a data structure
and a self-referential pointer which points to the next
node in the list.
⚫ The List ADT Functions is given below:
⚫ get() – Return an element from the list at any given
position.
⚫ insert() – Insert an element at any position of the list.
⚫ remove() – Remove the first occurrence of any
element from a non-empty list.
⚫ removeAt() – Remove the element at a specified
location from a non-empty list.
⚫ replace() – Replace an element at any position by
another element.
Generalized Linked List
⚫ A Generalized Linked List L, is defined as a
finite sequence of n>=0 elements, l1, l2, l3, l4,
…, ln, such that li are either atom or the list
of atoms. Thus
L = (l1, l2, l3, l4, …, ln)
where n is total number of nodes in the list.

⚫ To represent a list of items there are certain


assumptions about the node structure.
⚫ Flag = 1 implies that down pointer exists
⚫ Flag = 0 implies that next pointer exists
⚫ Data means the atom
⚫ Down pointer is the address of node which is down
GLL
⚫ To represent a list of items there are
certain assumptions about the node
structure.
⚫ Flag = 1 implies that down pointer exists
⚫ Flag = 0 implies that next pointer exists
⚫ Data means the atom
⚫ Down pointer is the address of node which
is down of the current node
⚫ Next pointer is the address of node which
is attached as the next node
GLL

⚫ Why Generalized Linked List?


Generalized linked lists are used because
although the efficiency of polynomial
operations using linked list is good but still,
the disadvantage is that the linked list is
unable to use multiple variable polynomial
equation efficiently. It helps us to represent
multi-variable polynomial along with the list
of elements.
⚫ Typical ‘C’ structure of Generalized Linked
List
⚫ typedef struct node {
⚫ char c; //Data
⚫ int index; //Flag
Enumeration

⚫ Enumeration is a user defined datatype in C


language. It is used to assign names to the
integral constants which makes a program easy
to read and maintain. The keyword “enum” is
used to declare an enumeration.
⚫ It increases readability of program
⚫ It improves maintainability of program
⚫ syntax of enum in C language,
⚫ enum enum_name{const1, const2, ....... };
⚫ The enum keyword is also used to define the
variables of enum type.
⚫ There are two ways to define the variables of
enum type as follows.
⚫ enum week{sunday, monday, tuesday,
wednesday, thursday, friday, saturday};
⚫ enum week day;
example of enum in C
⚫ #include<stdio.h>
⚫ enum week{Mon=10, Tue, Wed, Thur, Fri=10,
Sat=16, Sun};
⚫ enum day{Mond, Tues, Wedn, Thurs, Frid=18,
Satu=11, Sund};
⚫ int main() {
⚫ printf("The value of enum week:
%d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed, Thur, Fri,
Sat, Sun);
⚫ printf("The default value of enum day:
%d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues, Wedn, Thurs, Frid,
Satu, Sund);
⚫ return 0;
⚫ }
⚫ Output:
⚫ The value of enum week: 10111213101617 //next
Representation of multivariable polynomial

⚫ Polynomial Representation using Generalized


Linked List
The typical node structure will be:
⚫ Here Flag = 0 means variable is present
⚫ Flag = 1 means down pointer is present
⚫ Flag = 2 means coefficient and exponent is
present
Polynomial in Link List
Polynomial in Link List: example of addition
Polynomial Addition
⚫ What is polynomial addition in data
structure?
When two polynomials are added, the like
terms in the two polynomials are
combined. We use the term "like terms" to
refer to terms that have the same variable
and exponent.
Polynomial using Linked List

A polynomial is composed of different terms


where each of them holds a coefficient and an
exponent.
⚫ What is a polynomial?
⚫ A polynomial p(x) is the expression in
variable x which is in the form (axn + bxn-1 + ….
+ jx+ k), where a, b, c …., k fall in the category
of real numbers and 'n' is non negative
integer, which is called the degree of
polynomial.
⚫ An essential characteristic of the polynomial
is that each term in the polynomial
expression consists of two parts:
⚫ one is the coefficient
Algorithm

⚫ Create a new linked list, new Head to store the


resultant list.
⚫ Traverse both lists until one of them is null.
⚫ If any list is null insert the remaining node of
another list in the resultant list.
⚫ Otherwise compare the degree of both nodes,
a and b. Here three cases are possible:
1) If the degree of a and b is equal, we insert a
new node in the resultant list with the
coefficient equal to the sum of coefficients of a
and b and the same degree.
2) If the degree of a is greater than b, we insert
a new node in the resultant list with the
coefficient and degree equal to that of a.
3) If the degree of b is greater than a, we insert
Addition of two polynomials
⚫ Approach: We compare the power of the first
polynomial of both lists. If it is the same then we
simply add their coefficient and push them into the
resultant list otherwise we push the polynomial of
the list whose power is greater than the other
polynomial.
⚫ Pseudocode:
⚫ Declare variables that point to the head of the linked
list.
⚫ Compare the power of the first polynomial of both
lists.
⚫ If it is the same then add their coefficients and push
them into the resultant list. Also, increment both the
variables so that it points to the next polynomial.
⚫ Else, Push the polynomial of the list whose power is
greater than the other. Also, increment that particular
list.
⚫ Keep repeating the 2nd step until one of the
Points to Note with Polynomials:
⚫ Pseudocode
⚫ Declare variables that point to the head of the
linked list.

⚫ Compare the power of the first polynomial of both


lists.

⚫ If it is the same then add their coefficients and push


them into the resultant list. Also, increment both the
variables so that it points to the next polynomial.

⚫ Else, Push the polynomial of the list whose power is


greater than the other. Also, increment that particular
list.

⚫ Keep repeating the 2nd step until one of the


variables reaches the end of the list.
Polynomial Representation
Algorithm Polynomial addition
Polynomial Addition

⚫ The polynomial add function


⚫ * Adds two polynomial to a given variable
⚫ * @param my_poly ** result Stores the result
⚫ * @param my_poly * poly1 The first polynomial expression
⚫ * @param my_poly * poly2 The second polynomial
expression
⚫ * @return void
⚫ */
⚫ void my_add_poly(my_poly ** result, my_poly * poly1,
my_poly * poly2) {
⚫ my_poly * tmp_node; //Temporary storage for the linked
list
⚫ tmp_node = (my_poly *) malloc(sizeof(my_poly));
⚫ tmp_node->next = NULL;
⚫ *result = tmp_node; //Copy the head address to the result
linked list
⚫ //Loop while both of the linked lists have value
⚫ while(poly1 && poly2) {
⚫ if (poly1->pow > poly2->pow) {
⚫ tmp_node->pow = poly1->pow;
⚫ tmp_node->coeff = poly1->coeff;
⚫ poly1 = poly1->next;
⚫ }
⚫ else if (poly1->pow < poly2->pow) {
⚫ tmp_node->pow = poly2->pow;
⚫ tmp_node->coeff = poly2->coeff;
⚫ poly2 = poly2->next;
⚫ }
⚫ else {
⚫ tmp_node->pow = poly1->pow;
⚫ tmp_node->coeff = poly1->coeff + poly2->coeff;
⚫ poly1 = poly1->next;
⚫ poly2 = poly2->next;}
code

⚫ //Grow the linked list on condition


⚫ if(poly1 && poly2) {
⚫ tmp_node->next = (my_poly *)
malloc(sizeof(my_poly));
⚫ tmp_node = tmp_node->next;
⚫ tmp_node->next = NULL;
⚫ }
⚫ }
code

⚫ //Loop while either of the linked lists has value


⚫ while(poly1 || poly2) {
⚫ //We have to create the list at beginning
⚫ //As the last while loop will not create any unnecessary node
⚫ tmp_node->next = (my_poly *) malloc(sizeof(my_poly));
⚫ tmp_node = tmp_node->next;
⚫ tmp_node->next = NULL;
⚫ if(poly1) {
⚫ tmp_node->pow = poly1->pow;
⚫ tmp_node->coeff = poly1->coeff;
⚫ poly1 = poly1->next;
⚫ }
⚫ if(poly2) {
⚫ tmp_node->pow = poly2->pow;
⚫ tmp_node->coeff = poly2->coeff;
⚫ poly2 = poly2->next;
⚫ }}
⚫ printf("\nAddition Complete");
⚫ }

You might also like