SlideShare une entreprise Scribd logo
1  sur  131
MODULE-
3 LINKED
LIST
Department of ISE Acharya Institute of Technology
Mrs.Jimsha K Mathew
Assistant Professor
Department of ISE
Acharya Institute Of Technology
MODULE
3
TOPICS
Linked Lists: Definition, Representation of linked lists in Memory, Memory
allocation; Garbage Collection. Linked list operations: Traversing, Searching,
Insertion, and Deletion. Doubly Linked lists, Circular linked lists, and header linked
lists. Linked Stacks and Queues. Applications of Linked lists – Polynomials, Sparse
matrix representation. Programming Examples
Department of ISE Acharya Institute of Technology
LINKED LIST
• Linked List is a linear data structure.
• linked list elements are not stored at a contiguous location; the
elements are linked using pointers.
• Linked list is a collection of nodes linked together in a sequential way.
• Each node contains a data field and an address field which contains the
reference (address)of the next node.
Advantages of Linked Lists over Arrays
1.Efficient Memory Utilization: The memory of a linked list is not
pre-allocated. Memory is allocated whenever required and de-
allocated when it is no longer required.
2.Insertion and deletion operations are easier and efficient.
3.Manipulations: Without any prior idea of memory space available
we can perform the computations. Example, there is no “overflow
condition” while implementing stacks or queues.
4.Data can be stored in non-contiguous blocks of memory which
exhibits logical adjacency i.e. they are linked by pointers.
Department of ISE Acharya Institute of Technology
Disadvantages of Linked Lists
1.It requires extra space because each node requires to hold the
address of the next node within it (i.e. a pointer field).
2.Accessing a particular node in the list may take more time
compared with arrays because the list needs to be traversed from
the beginning.
Department of ISE Acharya Institute of Technology
Singly-linked lists vs. 1D-arrays
ID-array Singly-linked list
Fixed size: Resizing is expensive Dynamic size
Insertions and Deletions are inefficient: Elements
are usually shifted
Insertions and Deletions are efficient: No shifting
Random access i.e., efficient indexing No random access
 Not suitable for operations requiring
accessing elements by index such as sorting
No memory waste if the array is full or almost
full; otherwise may result in much memory waste.
Extra storage needed for references; however uses
exactly as much memory as it needs
Sequential access is faster because of greater
locality of references [Reason: Elements in
contiguous memory locations]
Sequential access is slow because of low locality
of references [Reason: Elements not in contiguous
memory locations]
Representation
• Each node in a list consists of at least two parts:
1) Data/info
2) Pointer /link (Or Reference) to the next node
• The first node is called the head. If the linked list is empty, then the value
of the head is NULL.
• The last node in the linked list can be identified because its next portion
points to NULL.
Linked List Data Structure
A linked list is a linear data structure, in which the elements are not stored at contiguous
memory locations. The elements in a linked list are linked using pointers as shown in the
below image:
Representing linked list in C
The following capabilities are needed to make linked representation
possible
•A mechanism to define the nodes structure.
This is done using self-referential structures.
•A way to create new nodes when we need them.
This is done using malloc( ) function.
•A way to remove nodes that we no longer need.
This is done using free( ) function.
Department of ISE Acharya Institute of Technology
Types of Linked lists
Following are the various types of linked list.
Singly Linked List − Item Navigation is forward only.
Doubly Linked List − Items can be navigated forward and backward way.
Circular Linked List − Last item contains link of the first element as next and and first
element has link to last element as prev.
linked list consists of nodes where each node contains a data field and a
reference(link) to the next node in the list.
Such a structure can be represented as:
struct node
{
int data;
struct node *next;
}
In C we can represent a node using a self referential structure.
struct node
{ int data;
struct node* next;
};
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.
Declare a pointer to node type
struct node *head,*one, *two ,*three ;
Representation
in C
• /* Allocate memory */
• one = (struct node *)malloc(sizeof(struct node));
• two = (struct node *)malloc(sizeof(struct node));
• three=(struct node *)malloc(sizeof(struct node));
• All the three pointers will contain address of newly created nodes using
malloc() function
One=100 Two=200
Three=300
/* Assign data values */
one->data = 1;
two->data = 2;
three->data=3;
1 2 3
One=100 Two=200
Three=300
/* Connect nodes */
one->next = two;
two->next = three;
three->next = NULL;
1 200 2 300 3 null
One=100 Two=200
Three=300
• /* Save address of first node in head */
head = one;
Linked list operations
• Node Creation
• Insertion
• Insertion at beginning
• Insertion after a specified node
• Insertion at the end
• Deletion
• Deletion from beginning
• Deletion after a specified node
• Deletion from the end
• Traversal
• Search
Singly Linked Lists
• Linked list is a linear collection of data elements called nodes
and there exists a logical relationship between nodes (i.e. given
the address of first node, any node in that list can be obtained).
• Forward direction only
The pictorial representation of a singly linked list is as shown below.
Department of ISE Acharya Institute of Technology
Each and every node has 2 fields.
•Info /data field – Here some useful information can be stored.
•Link /pointer field – This field contains address of the next node. So
this field should be of type pointer.
Note: A chain is a singly linked list that is compromised of zero or
more nodes. When the number of nodes is zero, the chain is empty.
The nodes of a chain are ordered so that the first node links to the
second, second to the third and so on. The last node of a chain has
a zero link (NULL).
Department of ISE Acharya Institute of Technology
Note:
Observations:
•head = NULL => List is empty.
•head ->next = NULL => There is one element in the List
•head ->next ! = NULL => There is more than one element in the
List
Department of ISE Acharya Institute of Technology
1. Function to create a n-
node list
void nodecreate()
{
Head=(struct node*)malloc(sizeof(structnode));
Head->data=data;
Head->next=null ;
temp=Head
for(i=2;i<=n;i++)
{
newnode=(struct node*)malloc(sizeof(struct node);
newnode->data=data
newnode->next=null;
temp->next=newnode;
temp=temp->next;
}
}
struct node
{
int data;
struct node *next;
} *Head,*newnode,*temp;
2(a). Insertion In singly linked list-Insertion at beginning
ALGORITHM:
• Allocate memory for new node
• Store data
• Change next of new node to point to head
• Change head to point to recently created node
Function to insert an element at the front end
Void insert_front()
{
temp = (struct node*)malloc(sizeof(struct node));
temp->data = item;
temp->next = head;
head=temp;
}
Department of ISE Acharya Institute of Technology
struct node
{
int data;
struct node *next;
} *head, *temp;
Insertion at theend
1. Allocate memory for new node
2. Store data
3. Traverse to last node
4. Change next of last node to recently created
node
2.(b) Function to insert an element at the rear(back) end
void insert_rear()
{
newnode=(struct node*)malloc(sizeof(struct node));
newnode ->data = item;
newnode ->next = NULL;
if(head = = NULL) //no node
{
head=newnode;
}
else {
temp = head; // node exists
while(temp->next != NULL)
{
temp= temp->next;
}
temp->next = newnode;
} Department of ISE Acharya Institute of Technology
struct node
{
int data;
struct node *next;
} *head, *temp,
*newnode;
2(c).Insert at a specified position
Algorithm:
• Allocate memory and store data for new node
• Traverse to node just before the required position of new node
• Change next pointers to include new node in between
• Step1 : create a new node
• Step 2: Traverse to the n-1th position of the linked list and connect the new
node with the n+1th node.
newNode->next = temp->next , where temp is the n-1th node.
• Step 4: Now at last connect the n-1th node with the new node i.e.
the n-1th node will now point to new node.
temp->next = newNode
Function to insert an item at a specified position(after a specified node)
void insert_pos( )
{
newnode=(struct node)malloc(sizeof(struct node));
newnode ->data = item;
newnode ->next = NULL;
temp=head;
if(head = = NULL && loc = = 1)// no elements in the list
head=newnode;
If else (loc= = 1) // insert at the beginning
{
newnode->next= head;
head=newnode;
}
}
Department of ISE Acharya Institute of Technology
else
{
for(i=1;i<loc;i++)
{
temp = temp->next;
}
newnode ->next =temp->next;
temp ->next = newnode;
}
}
DELETION
DELETION OF NODE
1. Deleting from Beginning of the list
2. Deleting from End of the list
3. Deleting a Specific Node
Delete from the beginning Algorithm:
Steps
• Break the pointer connection
• Set the next node as head
• Delete the node
Deletion Description
4 17
head
42
6
4 17
head
42
6
4 17
head
42
3(a).Function to delete an element at the front end
void delete_front()
{
if(head= = NULL) // no node
{
printf("list is emptyn");
}
else if(head ->next = = NULL) // only one
node
{
head=NULL;
free(head);
}
else
temp = head;
head= temp->next;
free(temp);
}
Department of ISE Acharya Institute of Technology
struct node
{
int data;
struct node *next;
} *head, *temp,
*newnode;
Deleting from the end
Steps
1. Search the Node to be deleted and call it temp
2. Store previous node call is as previous
3. Assign previous->next to temp->next
4. In this case, the temp->next will be Null so no difference from deletion at middle
5. Free(temp)
Deletion Description
4 17
head
42
6
4 17
head
42
6
4 17
6
head
3(b).Function to delete an element at the rear
end
void delete_rear()
{
if(head = = NULL) // no
node
{ printf("list is emptyn");
}
if(head ->next = = NULL) // only
one node
{
head=NULL;
free(head);
}
else {
temp = head;
while(temp->next != NULL)
}
{
ptr1 = temp;
temp = temp ->next;
}
ptr1->next = NULL;
free(temp);
}
}
Department of ISE Acharya Institute of Technology
struct node
{
int data;
struct node *next;
} struct node *head,
*temp, *ptr1;
Department of ISE
3(c).Function to delete a node from a specified location is
given
void delete_specloc( )
{
if(head = = NULL) // empty list
{
printf("the list is emptyn");
}
else
temp=head;
Acharya Institute of
T}echnology
for(i=1;i<loc;i++) {
ptr1=temp;
temp=temp->next;
}
ptr1->next=temp->next;
free(temp);
}
Function to display/Traverse the contents of the list
void display( )
{
if(head = = NULL)
{
printf("the list is emptyn");
}
else {
temp = head;
printf("the contents of the list are:n");
while(temp!= NULL)
{
printf("%d",temp->data);
temp= temp->next;
}
}}
Department of ISE Acharya Institute of Technology
Note:
1.To implement stacks using linked lists the functions required
are
•Insert_front( ), Delete_front and Display( ) OR
•Insert_rear( ), Delete_rear and Display( )
2.To implement queues using linked lists the function required
are
•Insert_front( ), Delete_rear and Display( ) OR
•Insert_rear( ), Delete_front and Display( )
3.To implement De-queues using linked lists the function
required are Insert_front( ), Delete_front, Insert_rear( ),
Delete_rear and Display( )
Department of ISE Acharya Institute of Technology
Other operations of a linked list
•Function to count the number of nodes in a list
int countnodes( )
{
int count = 0;
temp= head;
while(temp!= NULL)
{
count = count + 1;
temp = temp->next;
}
return count;
}
Department of ISE Acharya Institute of Technology
• Function to concatenate 2 lists
int concatenate( )
{
if(firsthead = = NULL)
return secondhead;
if(secondhead = = NULL)
return firsthead;
temp = firsthead;
while(temp->next!= NULL)
{
temp = temp->next;
}
temp->next = secondhead;
}
Department of ISE Acharya Institute of Technology
Function to search for an item in the list and display the
position if found
void search_item( )
{
int pos;
if(head= = NULL)
{
printf(“list is emptyn”);
return;
}
temp = head;
pos = 1;
while(temp != NULL && item ! =temp->data)
{
temp = temp->next;
pos = pos + 1;
}
if(temp = = NULL)
{
printf(“Unsuccessful searchn”);
return;
}
printf(“Successful search and item found at position %dn”, pos);
}
Department of ISE Acharya Institute of Technology
Disadvantages of Singly Linked List
•Given the address of a node in the list, it is difficult to find the
address of previous node.
•Traversing of list is possible only in the forward direction and
hence singly linked list is also termed as one-way list.
Doubly Linked List Representation
To increase the performance and efficiency of algorithms, it is required
to traverse the list in either forward or backward direction. Therefore a
two-way list called as doubly linked list can be made use of, so that
traversing from left to right (forward) or right to left (backward) is
possible.
Department of ISE Acharya Institute of Technology
DOUBLY LINKED LIST
Doubly linked lists
Each node points to not only successor but the predecessor
There are two NULL: at the first and last nodes in the list
 It is a way of going both directions in a linked list, forward and reverse.
 Many applications require a quick access to the predecessor node of some node in
list.
A
Head
B
 C 
Advantages over Singly-linked Lists
Quick update operations:
such as: insertions, deletions at both ends (head and tail), and also at the
middle of the list.
A node in a doubly-linked list store two references:
•A next link; that points to the next node in the list, and
•A prev link; that points to the previous node in the list.
REPRESENTATION OF A NODE IN DOUBLY LINKED
LIST
struct Node
{
struct Node *prev;
int data;
struct Node *next;
} * head;
Each node in the list consists of
•prev – Contains the address of the left node or previous
node
•data – It is the data to be processed.
•next – Contains the address of the right node or next
node
The structure declaration for each node is as shown
below struct node
{
int data;
struct node
*prev; struct
node *next;
};
Department of ISE Acharya Institute of Technology
In a singly linked list, we could traverse only in one direction, because each node
contains address of the next node and it doesn't have any record of its previous nodes.
However, doubly linked list overcome this limitation of singly linked list.
Due to the fact that, each node of the list contains the address of its previous node, we
can find all the details about the previous node as well by using the previous address
stored inside the previous part of each node.
Memory Representation of a doubly linked list
Operations on doubly linked list
 Node Creation (single node)
 Insertion at the beginning
 Insertion at the end
 Insertion after a specified location
 Deletion from beginning
 Deletion from end
 Deletion from a specified location
 Traversal
 searching
Node Creation
struct node
{
struct node *prev;
int data;
struct node *next;
};
struct node *head;
Function to insert an element at the front end of
DLL:
void insertfront ( )
{
newnode=(struct node*)malloc(sizeof(struct
node)); newnode ->data = item;
newnode ->prev = NULL;
newnode->next = NULL;
if(head = = NULL)
return newnode;
newnode ->next = head;
head->prev = newnode;
head=newnode;
return newnode;
}
Department of ISE Acharya Institute of Technology
struct node
{
struct node *prev;
int data;
struct node *next;
} * head,*newnode;
Function to insert an element at the rear end
void insertrear( )
{
newnode = (struct node*)malloc(sizeof(struct
node)); newnode ->data = item;
newnode ->prev=NULL;
newnode ->next = NULL;
if(head = = NULL)
return newnode ;
temp= head;
while(temp->next != NULL) {
temp = temp->next;
}
temp->next = newnode ;
newnode ->prev = temp;
}
Department of ISE Acharya Institute of Technology
Insertion in doubly linked list after Specified node
Int insert_specified ( )
{
newnode= (struct node *)malloc(sizeof(struct node));
newnode->next=NULL;
Newnode->prev=NULL;
int i, loc;
if(head == NULL)
{
return newnode;
}
else
{
printf("nEnter the locationn");
scanf("%d",&loc);
ptr=head;
for(i=1;i<loc;i++)
{
ptr = ptr->next;
}
newnode->data = item;
newnode->next = ptr->next;
newnode-> prev = ptr;
ptr->next->prev=newnode;
ptr->next = newnode;
printf("Node Insertedn");
}
}
DELETION IN DOUBLY LINKED LIST
10 20 30
200 300
300
200
100
NULL
temp=head
NUL
L
temp = head;
head = head -> next;
head -> prev = NULL;
free(temp);
head
NUL
L
200
void beginning_delete()
{
if(head == NULL)
{
printf("n List is empty”);
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("nNode Deletedn");
}
else
{
temp = head;
head = head -> next;
head -> prev = NULL;
free(temp);
printf("nNode Deletedn");
} }
DELETION AT THE BEGINNING
 Deletion of the last node in a doubly linked list needs traversing the
list in order to reach the last node of the list and then make pointer
adjustments at that position.
 In order to delete the last node of the list, we need to follow the
following steps.
•If the list is already empty then the condition head == NULL will
become true and therefore the operation can not be carried on.
•If there is only one node in the list then the condition head →
next == NULL become true. In this case, we just need to assign
the head of the list to NULL and free head in order to completely
delete the list
DELETION AT THE END
10 20 30
200 NUL
L
300
200
100
NULL
ptr=head
NUL
L
ptr -> prev -> next = NULL;
free(ptr);
ptr
100 200
void last_delete()
{
if(head == NULL)
{
printf("n UNDERFLOWn");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
}
DELETION AT THE END
else
{
ptr = head;
if(ptr->next != NULL)
{
ptr = ptr -> next;
}
ptr -> prev -> next = NULL;
free(ptr);
}
}
DELETION OF NODE FROM A SPECIFIED POSITION IN
DLL:
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
free(temp);
 Suppose you want to delete the second node from the list.
 Start traversing the linked list from the head until the position = 2
of the node to be deleted.
 Let the node at the position 2 of the list be temp.
 Assign the next pointer of temp to temp's previous
node's next pointer.
 Assign the temp's prev pointer to temp's next node's prev pointer.
 Delete the temp node.
void delete_given_position( )
{
int i;
temp = head;
for(i=1; i<position && temp!=NULL; i++)
{
temp = temp->next;
}
if(temp != NULL)
{
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
free(temp);
}
else
{
printf("Invalid position!n");
}}
Function to Traverse /display the contents of the
list
void display( )
{
if(head = = NULL)
{
printf("the list is emptyn");
return;
}
printf("the contents of the list are:n");
temp = head;
while(temp != NULL)
{
printf("%dn",temp->data);
temp= temp->next;}
}
Department of ISE Acharya Institute of Technology
Function to search for an item in the DLL and display the
position if found
void search_item( )
{
int pos;
if(head= = NULL)
{
printf(“list is emptyn”);
return;
}
temp = head;
pos = 1;
while(temp != NULL && item ! =temp->data)
{
temp = temp->next;
pos = pos + 1;
}
if(temp = = NULL)
{
printf(“Unsuccessful searchn”);
return;
}
printf(“Successful search and item found at position %dn”, pos);
}
Department of ISE Acharya Institute of Technology
Circular linked list
1. Circular singly linked list
2. Circular doubly 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 can have circular singly linked list as well as circular doubly linked list.
• We traverse a circular singly linked list until we reach the same node where we
started.
• The circular singly liked list has no beginning and no ending.
• There is no null value present in the next part of any of the nodes.
• The following image shows a circular singly linked list.
Circular singly linked list
 Circular linked list are mostly used in task maintenance in operating systems.
 There are many examples where circular linked list are being used in computer science
including browser surfing where a record of pages visited in the past by the user, is
maintained in the form of circular linked lists and can be accessed again on clicking the
previous button.
Circular Singly Linked List
In normal singly linked list,
•The link part of the last node has NULL value, specifying that it is the
last node.
•Given the address of any node ‘x’, it is only possible to reach the nodes
which follow ‘x’ and it is not possible to reach the nodes that precedes
‘x’ (previous nodes). To reach the nodes that precedes ‘x’, it is required
to preserve a pointer variable first, which contains the address of the
first node in the list and use this for traversing.
•Also, given the address of the first node to get the address of the last
node, the list has to be traversed from the beginning till the last node is
reached.
Department of ISE Acharya Institute of Technology
These disadvantages can be overcome using circular singly linked
list. In a circular singly linked list the link field of the last node points
to the first node in the list, which makes the list a circular one. The
pictorial representation is as shown below.
Department of ISE Acharya Institute of Technology
OPERATIONS OF CIRCULAR SINGLY LINKED LIST(CSLL):
Department of ISE Acharya Institute of Technology
 NODE CREATION
 INSERTION
 DELETION
 TRAVERSING/DISPLAY
 SEARCHING
NODE CREATION:
•Here the link field of the last node contains address of the first node.
•In the following functions we use the structure definition as shown
below. struct node
{
int data;
struct node *next;
}*head;
Department of ISE Acharya Institute of Technology
Insertion
20
300
10
200
300
200
temp->next = newnode;
newnode->next = head;
return last;
temp
30 200
600
600
head
head
Insertion into circular singly linked list at beginning
void beg_insert(int item)
{
newnode= (struct node *)malloc(sizeof(struct n
ode));
newnode-> data = item;
if(head == NULL) //no nodes exist
{
head = newnode;
newnode -> next = head;
}
else
{
temp = head;
while(temp->next != head)
{
temp = temp->next;
}
newnode->next = head;
temp -> next = newnode;
head = newnode;
}
}
Insertion into circular singly linked list at beginning
Function to insert an element at the rear end-
CSLL
Department of ISE Acharya Institute of Technology
void lastinsert( )
{
newnode = (struct node *)malloc(sizeof(struct nod
e));
newnode->data = item;
if(head == NULL)
{
head = newnode;
newnode-> next = head;
}
else
{
temp = head;
while(temp -> next != head)
{
temp = temp -> next;
}
temp -> next = newnode;
newnode -> next = head;
}
}
Function to insert an item at a specified position(after a specified node) -
CSLL
void insert_pos( )
{ newnode=(struct node)malloc(sizeof(struct node));
newnode ->data = item;
temp=head;
if(head = = NULL && loc = = 1)// no elements in the list
head=newnode;
Newnode->next=head
}
Department of ISE Acharya Institute of Technology
else
{
for(i=1;i<loc;i++)
{
temp = temp->next;
}
newnode ->next =temp->next;
temp ->next = newnode;
}
}
Deletion from circular singly linked list at beginning:
void beg_delete()
{
if(head == NULL)
{
printf("nUNDERFLOWn");
}
else if(head->next == head) // 1 node
{
head = NULL;
free(head);
printf("nNode Deletedn");
}
else
{
ptr = head;
while(ptr -> next != head)
{
ptr = ptr -> next;
}
ptr->next = head->next;
free(head);
head = ptr->next;
printf("nNode Deletedn");
}
}
Deletion from circular singly linked list at END:
void last_delete()
{
if(head==NULL)
{
printf("nUNDERFLOWn");
}
else if (head ->next == head)
{
head = NULL;
free(head);
printf("nNode Deletedn");
}
else
{
ptr = head;
while(ptr ->next != head)
{
preptr=ptr;
ptr = ptr->next;
}
preptr->next = ptr -> next;
free(ptr);
printf("nNode Deletedn");
}
}
Function to display/Traverse the contents of the list
IN CSLL
void display( )
{
if(head = = NULL)
{
printf("the list is emptyn");
}
else {
temp = head;
printf("the contents of the list are:n");
while(temp!= head)
{
printf("%d",temp->data);
temp= temp->next;
}
}} Department of ISE Acharya Institute of Technology
Function to search for an item in the CSLL and display the
position if found
void search_item( )
{
int pos;
if(head= = NULL)
{
printf(“list is emptyn”);
return;
}
temp = head;
pos = 1;
while(temp ->next != head && item ! =temp->data)
{
temp = temp->next;
pos = pos + 1;
}
if(temp->next = = head)
{
printf(“Unsuccessful searchn”);
return;
}
printf(“Successful search and item found at position %dn”, pos);
}
Department of ISE Acharya Institute of Technology
Circular Doubly Linked List -CDLL
Department of ISE Acharya Institute of Technology
OPERATIONS:
 NODE CREATION
 INSERTION
 DELETION
 TRAVERSING/DISPLAY
 SEARCHING
NODE CREATION:
struct node
{
int data;
struct node
*next; struct
node *prev;
} *head;
Department of ISE Acharya Institute of Technology
void beg_insert( )
{
newnode = (struct node *)malloc(sizeof(struct node));
newnode ->data=item;
if(head==NULL)
{
head = newnode;
newnode -> next = head;
newnode -> prev = head;
}
else
{
temp = head;
while(temp -> next != head)
{
temp = temp -> next;
}
temp -> next = newnode;
newnode -> prev = temp;
head -> prev = newnode;
newnode -> next = head;
head = newnode;
}
printf("Node Inserted");
}
}
Insertion into circular doubly linked list at beginning
Insertion into circular doubly linked list at END
void insertion_last( )
{
newnode
= (struct node *) malloc(sizeof(struct node));
newnode ->data=item;
if(head == NULL)
{
head = newnode;
newnode -> next = head;
newnode -> prev = head;
}
else
{
temp = head;
while(temp->next !=head)
{
temp = temp->next;
}
temp->next = newnode;
newnode ->prev=temp;
head -> prev = newnode;
newnode -> next = head;
}
}
printf("nNode Insertedn");
}
Deletion from circular doubly linked list -Beginning
void deletion_beginning()
{
if(head == NULL)
{
printf("n UNDERFLOWn");
}
else if(head->next == head)
{
head = NULL;
free(head);
}
else
{
temp = head;
while(temp -> next != head)
{
temp = temp -> next;
}
temp -> next = head -> next;
head -> next -> prev = temp;
free(head);
head = temp -> next;
}
}
Deletion from circular doubly linked list -END
void deletion_last()
{
if(head == NULL)
{
printf("n UNDERFLOWn");
}
else if(head->next == head)
{
head = NULL;
free(head);
}
else
{
temp= head;
while(temp >next != head)
{
temp = temp -> next;
}
temp -> prev -> next = head;
head -> prev = temp -> prev;
free(temp);
}
}
Linked list implementation of stack
 Instead of using array, we can also use linked list to implement stack. Linked list allocates the memory
dynamically. However, time complexity in both the scenario is same for all the operations i.e. push, pop
and peek.
 In linked list implementation of stack, the nodes are maintained non-contiguously in the memory. Each
node contains a pointer to its immediate successor node in the stack. Stack is said to be overflow if the
space left in the memory heap is not enough to create a node.
Representation
Adding a node/element to the stack (Push operation)
Algorithm
Step 1 - Create a newNode with given value.
Step 2 - Check whether stack is Empty (top == NULL)
Step 3 - If it is Empty, then set newNode → next = NULL.
Step 4 - If it is Not Empty, then set newNode → next = top.
Step 5 - Finally, set top = newNode.
Time Complexity : o(1)
void push ()
{
newnode =(struct node*)malloc(sizeof(struct node));
{
printf("Enter the value");
scanf("%d",&val);
if(top==NULL) //no elements in stack
{
newnode->data= item;
newnode-> next = NULL;
top=newnode;
}
else
{
newnode->data = item;
newnode->next = top;
top=newnode;
}
printf("Item pushed");
}
}
struct node
{
int data;
struct node *next;
} *top;
Deleting a node/element from the stack (POP operation)
Algorithm:
Step 1 - Check whether stack is Empty (top == NULL).
Step 2 - If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!" and terminate the function
Step 3 - If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
Step 4 – Decrement top.
Step 5 - Finally, delete 'temp'. (free(temp)).
Time Complexity : o(n)
void pop()
{
int item;
if (top == NULL)
{
printf("Underflow");
}
else
{
item = top->data;
temp= top;
top = top->next;
free(temp);
}
}
Display the nodes (Traversing)
 Displaying all the nodes of a stack needs traversing all the nodes of the linked list
organized in the form of stack. For this purpose, we need to follow the following steps.
 Copy the head pointer into a temporary pointer.
 Move the temporary pointer through all the nodes of the list and print the value field
attached to every node.
Time Complexity : o(n)
void display()
{
ptr=top;
if(ptr == NULL)
{
printf("Stack is emptyn");
}
else
{
printf("Printing Stack elements n");
while(ptr!=NULL)
{
printf("%dn",ptr->val);
ptr = ptr->next;
}
}
}
Queue implementation Using Linked List
 Queue using an array is not suitable when we don't know the size of data which we are going to use.
 A queue data structure can be implemented using a linked list data structure.
 The queue which is implemented using a linked list can work for an unlimited number of values.
 In linked list implementation of a queue, the last inserted node is always pointed by 'rear' and the first
node is always pointed by 'front'.
enQueue(value) - Inserting an element into the Queue
Step 1: Allocate the space for the new node PTR
Step 2: SET PTR -> DATA = VAL
Step 3: IF FRONT = NULL
SET FRONT = REAR = PTR
SET FRONT -> NEXT = REAR -> NEXT = NULL
ELSE
SET REAR -> NEXT = PTR
SET REAR = PTR
SET REAR -> NEXT = NULL
[END OF IF]
Step 4: END
void enqueue( )
{
ptr = (struct node *) malloc (sizeof(struct no
de));
ptr -> data = item;
if(front == NULL)
{
front = ptr;
rear = ptr;
rear -> next = NULL;
}
else
{
rear -> next = ptr;
rear = ptr;
rear->next = NULL;
}
}
}
deQueue() - Deleting an Element from Queue
Step 1: IF FRONT = NULL
Write " Underflow "
Go to Step 5
[END OF IF]
Step 2: SET PTR = FRONT
Step 3: SET FRONT = FRONT -> NEXT
Step 4: FREE PTR
Step 5: END
void delete (struct node *ptr)
{
if(front == NULL)
{
printf("nUNDERFLOWn");
}
else
{
ptr = front;
front = front -> next;
free(ptr);
}
}
APPLICATIONS OF LINKED LIST
Polynomial – Using Singly
Linked List Representation
Consider the polynomial 9x3 + 7x2 + 6x + 9. This polynomial can be
represented using a singly linked list as shown below.
Every node has 3
fields cf – coefficient
field
px – power of x
next – contains the address of next
node.
Department of ISE Acharya Institute of Technology
Polynomial Representation using Linked List
A Polynomial has mainly two fields. exponent and coefficient.
Node of a Polynomial:
For example 3x^2 + 5x + 7 will represent as follows.
In each node the exponent field will store the corresponding exponent and the coefficient field will store the corresponding coefficient. Link field
points to the next item in the 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
 other is the exponent
• The sign of each coefficient and exponent is stored within the coefficient and the
exponent itself
• Additional terms having equal exponent is possible one
• The storage allocation for each term in the polynomial must be done in ascending and
descending order of their exponent
Therefore, the structure declaration to represent this node
will be struct polynode
{
int
cf;
int
px;
struct polynode *next;
}*head;
Department of ISE Acharya Institute of Technology
ADDITION OF 2 POLYNOMIALS
Input: 1st number = 5x^2 + 4x^1 + 2x^0
2nd number = 5x^1 + 5x^0
Output: 5x^2 + 9x^1 + 7x^0
Algorithm:
Step 1: Compare the exponent of P and the corresponding exponent of q.
Step 2:if expo(p) < expo(q) added the terms pointer to q to the resultant list and now
advanced the q pointer.
Step 3:expo(p) > expo(q) added the terms pointer to p to the resultant list and now
advanced the p pointer.
Step 3:If expo(p) = expo(q) Add the coefficients of these two terms and link this to the
resultant list and advance the pointers p and q to their next nodes.
Step 4:If there is no node in the second polynomial to compare with, so the last node in
the first polynomial is added to the end of the resultant linked list.
Step 5:If there is no node in the first polynomial to compare with, so the last node in the
second polynomial is added to the end of the resultant linked list.
Example:
p= 30x2 + 20x + 100 —————(1)
Q= 60x3 + 50x2 + 60x——————(2)
Case1:expo(p) < expo(q)
Case2: expo(p) = expo(q)
In the above figure, you will notice that there is no node in the second polynomial to
compare with.
you can understand in a better way after seeing the figure, so the last node in the first
polynomial is added to the end of the resultant linked list.
The next below figure is the output which comes Polynomials Addition of two
polynomials.
Resultant linked list
Note: link field of last node contains the address of head and link field of
header node points to the first node of the list.
Every node has 3 fields
•cf – coefficient field
•px – power of x
•link – contains the address of next node.
Therefore, the structure declaration to represent this node
will be struct node
{
int cf;
int
px;
struct node *link;
};
typedef struct node* NODE;
Program to add two Polynomials using Circular Singly Linked List header
node
Department of ISE Acharya Institute of Technology
void sum()
{
node=(struct node*)malloc(sizeof(struct node));
head3=node;
ptr1=head1;
ptr2=head2;
while(ptr1!=NULL && ptr2!=NULL)
{
ptr=node;
if (ptr1->pow < ptr2->pow ) s
{
node->coff=ptr2->coff;
node->pow=ptr2->pow;
ptr2=ptr2->next;
}
function to add 2 polynomials:
else if ( ptr1->pow > ptr2->pow )
{
node->coff=ptr1->coff;
node->pow=ptr1->pow;
ptr1=ptr1->next;
}
else // ptr1->pow == ptr2->pow
{
node->coff=ptr2->coff+ptr1->coff;
node->pow=ptr2->pow;
ptr1=ptr1->next;
ptr2=ptr2->next;
} }
if (ptr1==NULL)
{
while(ptr2!=NULL)
{
node->coff=ptr2->coff;
node->pow=ptr2->pow;
ptr2=ptr2->next;
} }
else if (ptr2==NULL)
{
while(ptr1!=NULL)
{
node->coff=ptr1->coff;
node->pow=ptr1->pow;
ptr1=ptr1->next;
}
}}
Sparse matrix-Linked List Representation
In linked list representation, linked list data structure is
used to represent a sparse matrix. In linked list
representation, each node consists of four fields
whereas, in array representation, there are three fields,
i.e., row, column, and value.
The following are the fields in the linked list:
•Row: It is an index of row where a non-zero element is
located.
•Column: It is an index of column where a non-zero
element is located.
•Value: It is the value of the non-zero element which is
located at the index (row, column).
•Next node: It stores the address of the next node.
 In the above figure, sparse represented in the linked
list form. In the node, first field represents the index of
row, second field represents the index of column, third
field represents the value and fourth field contains the
address of the next node.

Contenu connexe

Similaire à module 3-.pptx

DS Module 03.pdf
DS Module 03.pdfDS Module 03.pdf
DS Module 03.pdfSonaPathak5
 
Unit ii(dsc++)
Unit ii(dsc++)Unit ii(dsc++)
Unit ii(dsc++)Durga Devi
 
Data Structures_Linked List
Data Structures_Linked ListData Structures_Linked List
Data Structures_Linked ListThenmozhiK5
 
4 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart14 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart1SSE_AndyLi
 
Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Getachew Ganfur
 
Linked list in Data Structure and Algorithm
Linked list in Data Structure and Algorithm Linked list in Data Structure and Algorithm
Linked list in Data Structure and Algorithm KristinaBorooah
 
Funddamentals of data structures
Funddamentals of data structuresFunddamentals of data structures
Funddamentals of data structuresGlobalidiots
 
DS Module 1.pptx
DS Module 1.pptxDS Module 1.pptx
DS Module 1.pptxSaralaT3
 
Linked List Presentation in data structurepptx
Linked List Presentation in data structurepptxLinked List Presentation in data structurepptx
Linked List Presentation in data structurepptxnikhilcse1
 
Deletion from single way linked list and search
Deletion from single way linked list and searchDeletion from single way linked list and search
Deletion from single way linked list and searchEstiak Khan
 

Similaire à module 3-.pptx (20)

Linked list (1).pptx
Linked list (1).pptxLinked list (1).pptx
Linked list (1).pptx
 
DS Unit 2.ppt
DS Unit 2.pptDS Unit 2.ppt
DS Unit 2.ppt
 
DS Module 03.pdf
DS Module 03.pdfDS Module 03.pdf
DS Module 03.pdf
 
Unit ii(dsc++)
Unit ii(dsc++)Unit ii(dsc++)
Unit ii(dsc++)
 
Linked list
Linked listLinked list
Linked list
 
Link list
Link listLink list
Link list
 
Unit 5 linked list
Unit   5 linked listUnit   5 linked list
Unit 5 linked list
 
Linkedlists
LinkedlistsLinkedlists
Linkedlists
 
Data Structures_Linked List
Data Structures_Linked ListData Structures_Linked List
Data Structures_Linked List
 
4 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart14 chapter3 list_stackqueuepart1
4 chapter3 list_stackqueuepart1
 
Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
Linked list in Data Structure and Algorithm
Linked list in Data Structure and Algorithm Linked list in Data Structure and Algorithm
Linked list in Data Structure and Algorithm
 
Linked List
Linked ListLinked List
Linked List
 
Funddamentals of data structures
Funddamentals of data structuresFunddamentals of data structures
Funddamentals of data structures
 
DS Module 1.pptx
DS Module 1.pptxDS Module 1.pptx
DS Module 1.pptx
 
Data structure
 Data structure Data structure
Data structure
 
Linked List Presentation in data structurepptx
Linked List Presentation in data structurepptxLinked List Presentation in data structurepptx
Linked List Presentation in data structurepptx
 
Linked list
Linked list Linked list
Linked list
 
Deletion from single way linked list and search
Deletion from single way linked list and searchDeletion from single way linked list and search
Deletion from single way linked list and search
 

Plus de kumarkaushal17

Open Source Cloud Computing (1).pptx
Open Source Cloud Computing (1).pptxOpen Source Cloud Computing (1).pptx
Open Source Cloud Computing (1).pptxkumarkaushal17
 
Chat application firebase.pptx1.pptx
Chat application firebase.pptx1.pptxChat application firebase.pptx1.pptx
Chat application firebase.pptx1.pptxkumarkaushal17
 
todd-ncts-2011-110828224616-phpapp02 (1).pptx
todd-ncts-2011-110828224616-phpapp02 (1).pptxtodd-ncts-2011-110828224616-phpapp02 (1).pptx
todd-ncts-2011-110828224616-phpapp02 (1).pptxkumarkaushal17
 
osi-security-architectureppt.pptx
osi-security-architectureppt.pptxosi-security-architectureppt.pptx
osi-security-architectureppt.pptxkumarkaushal17
 
DOC-20230427-WA0009..pptx
DOC-20230427-WA0009..pptxDOC-20230427-WA0009..pptx
DOC-20230427-WA0009..pptxkumarkaushal17
 
DOC-20230427-WA0010..pptx
DOC-20230427-WA0010..pptxDOC-20230427-WA0010..pptx
DOC-20230427-WA0010..pptxkumarkaushal17
 
DOC-20230427-WA0012..pptx
DOC-20230427-WA0012..pptxDOC-20230427-WA0012..pptx
DOC-20230427-WA0012..pptxkumarkaushal17
 
4. OPTIMIZATION NN AND FL.pptx
4. OPTIMIZATION NN AND FL.pptx4. OPTIMIZATION NN AND FL.pptx
4. OPTIMIZATION NN AND FL.pptxkumarkaushal17
 
Cloud_Deployment_Model (1).pptx
Cloud_Deployment_Model (1).pptxCloud_Deployment_Model (1).pptx
Cloud_Deployment_Model (1).pptxkumarkaushal17
 
pending-1664760315-2 knowledge based agent student.pptx
pending-1664760315-2 knowledge based agent student.pptxpending-1664760315-2 knowledge based agent student.pptx
pending-1664760315-2 knowledge based agent student.pptxkumarkaushal17
 
pending-1664760315-2 knowledge based agent student.pptx
pending-1664760315-2 knowledge based agent student.pptxpending-1664760315-2 knowledge based agent student.pptx
pending-1664760315-2 knowledge based agent student.pptxkumarkaushal17
 
cs344-lect4-logic-14jan08.ppt
cs344-lect4-logic-14jan08.pptcs344-lect4-logic-14jan08.ppt
cs344-lect4-logic-14jan08.pptkumarkaushal17
 
dbmspresentation-161126155322.pptx
dbmspresentation-161126155322.pptxdbmspresentation-161126155322.pptx
dbmspresentation-161126155322.pptxkumarkaushal17
 
MYSQL GROUP FUNCTION.pptx
MYSQL GROUP FUNCTION.pptxMYSQL GROUP FUNCTION.pptx
MYSQL GROUP FUNCTION.pptxkumarkaushal17
 

Plus de kumarkaushal17 (20)

RM 4 UNIT.pptx
RM 4 UNIT.pptxRM 4 UNIT.pptx
RM 4 UNIT.pptx
 
Open Source Cloud Computing (1).pptx
Open Source Cloud Computing (1).pptxOpen Source Cloud Computing (1).pptx
Open Source Cloud Computing (1).pptx
 
Chat application firebase.pptx1.pptx
Chat application firebase.pptx1.pptxChat application firebase.pptx1.pptx
Chat application firebase.pptx1.pptx
 
5 UNIT RM.pptx
5 UNIT RM.pptx5 UNIT RM.pptx
5 UNIT RM.pptx
 
todd-ncts-2011-110828224616-phpapp02 (1).pptx
todd-ncts-2011-110828224616-phpapp02 (1).pptxtodd-ncts-2011-110828224616-phpapp02 (1).pptx
todd-ncts-2011-110828224616-phpapp02 (1).pptx
 
osi-security-architectureppt.pptx
osi-security-architectureppt.pptxosi-security-architectureppt.pptx
osi-security-architectureppt.pptx
 
Microservice.pptx
Microservice.pptxMicroservice.pptx
Microservice.pptx
 
DOC-20230427-WA0009..pptx
DOC-20230427-WA0009..pptxDOC-20230427-WA0009..pptx
DOC-20230427-WA0009..pptx
 
DOC-20230427-WA0010..pptx
DOC-20230427-WA0010..pptxDOC-20230427-WA0010..pptx
DOC-20230427-WA0010..pptx
 
DOC-20230427-WA0012..pptx
DOC-20230427-WA0012..pptxDOC-20230427-WA0012..pptx
DOC-20230427-WA0012..pptx
 
Semiservice.pptx
Semiservice.pptxSemiservice.pptx
Semiservice.pptx
 
4. OPTIMIZATION NN AND FL.pptx
4. OPTIMIZATION NN AND FL.pptx4. OPTIMIZATION NN AND FL.pptx
4. OPTIMIZATION NN AND FL.pptx
 
Cloud_Deployment_Model (1).pptx
Cloud_Deployment_Model (1).pptxCloud_Deployment_Model (1).pptx
Cloud_Deployment_Model (1).pptx
 
pending-1664760315-2 knowledge based agent student.pptx
pending-1664760315-2 knowledge based agent student.pptxpending-1664760315-2 knowledge based agent student.pptx
pending-1664760315-2 knowledge based agent student.pptx
 
pending-1664760315-2 knowledge based agent student.pptx
pending-1664760315-2 knowledge based agent student.pptxpending-1664760315-2 knowledge based agent student.pptx
pending-1664760315-2 knowledge based agent student.pptx
 
cs344-lect4-logic-14jan08.ppt
cs344-lect4-logic-14jan08.pptcs344-lect4-logic-14jan08.ppt
cs344-lect4-logic-14jan08.ppt
 
dbmspresentation-161126155322.pptx
dbmspresentation-161126155322.pptxdbmspresentation-161126155322.pptx
dbmspresentation-161126155322.pptx
 
MYSQL GROUP FUNCTION.pptx
MYSQL GROUP FUNCTION.pptxMYSQL GROUP FUNCTION.pptx
MYSQL GROUP FUNCTION.pptx
 
DS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptxDS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptx
 
IPv4-ppt.k.pptx
IPv4-ppt.k.pptxIPv4-ppt.k.pptx
IPv4-ppt.k.pptx
 

Dernier

Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 

Dernier (20)

Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 

module 3-.pptx

  • 1. MODULE- 3 LINKED LIST Department of ISE Acharya Institute of Technology Mrs.Jimsha K Mathew Assistant Professor Department of ISE Acharya Institute Of Technology
  • 2. MODULE 3 TOPICS Linked Lists: Definition, Representation of linked lists in Memory, Memory allocation; Garbage Collection. Linked list operations: Traversing, Searching, Insertion, and Deletion. Doubly Linked lists, Circular linked lists, and header linked lists. Linked Stacks and Queues. Applications of Linked lists – Polynomials, Sparse matrix representation. Programming Examples Department of ISE Acharya Institute of Technology
  • 3. LINKED LIST • Linked List is a linear data structure. • linked list elements are not stored at a contiguous location; the elements are linked using pointers. • Linked list is a collection of nodes linked together in a sequential way. • Each node contains a data field and an address field which contains the reference (address)of the next node.
  • 4. Advantages of Linked Lists over Arrays 1.Efficient Memory Utilization: The memory of a linked list is not pre-allocated. Memory is allocated whenever required and de- allocated when it is no longer required. 2.Insertion and deletion operations are easier and efficient. 3.Manipulations: Without any prior idea of memory space available we can perform the computations. Example, there is no “overflow condition” while implementing stacks or queues. 4.Data can be stored in non-contiguous blocks of memory which exhibits logical adjacency i.e. they are linked by pointers. Department of ISE Acharya Institute of Technology
  • 5. Disadvantages of Linked Lists 1.It requires extra space because each node requires to hold the address of the next node within it (i.e. a pointer field). 2.Accessing a particular node in the list may take more time compared with arrays because the list needs to be traversed from the beginning. Department of ISE Acharya Institute of Technology
  • 6. Singly-linked lists vs. 1D-arrays ID-array Singly-linked list Fixed size: Resizing is expensive Dynamic size Insertions and Deletions are inefficient: Elements are usually shifted Insertions and Deletions are efficient: No shifting Random access i.e., efficient indexing No random access  Not suitable for operations requiring accessing elements by index such as sorting No memory waste if the array is full or almost full; otherwise may result in much memory waste. Extra storage needed for references; however uses exactly as much memory as it needs Sequential access is faster because of greater locality of references [Reason: Elements in contiguous memory locations] Sequential access is slow because of low locality of references [Reason: Elements not in contiguous memory locations]
  • 7. Representation • Each node in a list consists of at least two parts: 1) Data/info 2) Pointer /link (Or Reference) to the next node • The first node is called the head. If the linked list is empty, then the value of the head is NULL. • The last node in the linked list can be identified because its next portion points to NULL.
  • 8. Linked List Data Structure A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image:
  • 9. Representing linked list in C The following capabilities are needed to make linked representation possible •A mechanism to define the nodes structure. This is done using self-referential structures. •A way to create new nodes when we need them. This is done using malloc( ) function. •A way to remove nodes that we no longer need. This is done using free( ) function. Department of ISE Acharya Institute of Technology
  • 10. Types of Linked lists Following are the various types of linked list. Singly Linked List − Item Navigation is forward only. Doubly Linked List − Items can be navigated forward and backward way. Circular Linked List − Last item contains link of the first element as next and and first element has link to last element as prev.
  • 11. linked list consists of nodes where each node contains a data field and a reference(link) to the next node in the list. Such a structure can be represented as: struct node { int data; struct node *next; }
  • 12. In C we can represent a node using a self referential structure. struct node { int data; struct node* next; }; 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. Declare a pointer to node type struct node *head,*one, *two ,*three ; Representation in C
  • 13. • /* Allocate memory */ • one = (struct node *)malloc(sizeof(struct node)); • two = (struct node *)malloc(sizeof(struct node)); • three=(struct node *)malloc(sizeof(struct node)); • All the three pointers will contain address of newly created nodes using malloc() function One=100 Two=200 Three=300
  • 14. /* Assign data values */ one->data = 1; two->data = 2; three->data=3; 1 2 3 One=100 Two=200 Three=300
  • 15. /* Connect nodes */ one->next = two; two->next = three; three->next = NULL; 1 200 2 300 3 null One=100 Two=200 Three=300
  • 16. • /* Save address of first node in head */ head = one;
  • 17. Linked list operations • Node Creation • Insertion • Insertion at beginning • Insertion after a specified node • Insertion at the end • Deletion • Deletion from beginning • Deletion after a specified node • Deletion from the end • Traversal • Search
  • 18. Singly Linked Lists • Linked list is a linear collection of data elements called nodes and there exists a logical relationship between nodes (i.e. given the address of first node, any node in that list can be obtained). • Forward direction only The pictorial representation of a singly linked list is as shown below. Department of ISE Acharya Institute of Technology
  • 19. Each and every node has 2 fields. •Info /data field – Here some useful information can be stored. •Link /pointer field – This field contains address of the next node. So this field should be of type pointer. Note: A chain is a singly linked list that is compromised of zero or more nodes. When the number of nodes is zero, the chain is empty. The nodes of a chain are ordered so that the first node links to the second, second to the third and so on. The last node of a chain has a zero link (NULL). Department of ISE Acharya Institute of Technology
  • 20. Note: Observations: •head = NULL => List is empty. •head ->next = NULL => There is one element in the List •head ->next ! = NULL => There is more than one element in the List Department of ISE Acharya Institute of Technology
  • 21. 1. Function to create a n- node list void nodecreate() { Head=(struct node*)malloc(sizeof(structnode)); Head->data=data; Head->next=null ; temp=Head for(i=2;i<=n;i++) { newnode=(struct node*)malloc(sizeof(struct node); newnode->data=data newnode->next=null; temp->next=newnode; temp=temp->next; } } struct node { int data; struct node *next; } *Head,*newnode,*temp;
  • 22. 2(a). Insertion In singly linked list-Insertion at beginning ALGORITHM: • Allocate memory for new node • Store data • Change next of new node to point to head • Change head to point to recently created node
  • 23. Function to insert an element at the front end Void insert_front() { temp = (struct node*)malloc(sizeof(struct node)); temp->data = item; temp->next = head; head=temp; } Department of ISE Acharya Institute of Technology struct node { int data; struct node *next; } *head, *temp;
  • 24. Insertion at theend 1. Allocate memory for new node 2. Store data 3. Traverse to last node 4. Change next of last node to recently created node
  • 25. 2.(b) Function to insert an element at the rear(back) end void insert_rear() { newnode=(struct node*)malloc(sizeof(struct node)); newnode ->data = item; newnode ->next = NULL; if(head = = NULL) //no node { head=newnode; } else { temp = head; // node exists while(temp->next != NULL) { temp= temp->next; } temp->next = newnode; } Department of ISE Acharya Institute of Technology struct node { int data; struct node *next; } *head, *temp, *newnode;
  • 26. 2(c).Insert at a specified position Algorithm: • Allocate memory and store data for new node • Traverse to node just before the required position of new node • Change next pointers to include new node in between
  • 27. • Step1 : create a new node • Step 2: Traverse to the n-1th position of the linked list and connect the new node with the n+1th node. newNode->next = temp->next , where temp is the n-1th node.
  • 28. • Step 4: Now at last connect the n-1th node with the new node i.e. the n-1th node will now point to new node. temp->next = newNode
  • 29. Function to insert an item at a specified position(after a specified node) void insert_pos( ) { newnode=(struct node)malloc(sizeof(struct node)); newnode ->data = item; newnode ->next = NULL; temp=head; if(head = = NULL && loc = = 1)// no elements in the list head=newnode; If else (loc= = 1) // insert at the beginning { newnode->next= head; head=newnode; } } Department of ISE Acharya Institute of Technology else { for(i=1;i<loc;i++) { temp = temp->next; } newnode ->next =temp->next; temp ->next = newnode; } }
  • 31. DELETION OF NODE 1. Deleting from Beginning of the list 2. Deleting from End of the list 3. Deleting a Specific Node
  • 32. Delete from the beginning Algorithm: Steps • Break the pointer connection • Set the next node as head • Delete the node
  • 33. Deletion Description 4 17 head 42 6 4 17 head 42 6 4 17 head 42
  • 34. 3(a).Function to delete an element at the front end void delete_front() { if(head= = NULL) // no node { printf("list is emptyn"); } else if(head ->next = = NULL) // only one node { head=NULL; free(head); } else temp = head; head= temp->next; free(temp); } Department of ISE Acharya Institute of Technology struct node { int data; struct node *next; } *head, *temp, *newnode;
  • 35. Deleting from the end Steps 1. Search the Node to be deleted and call it temp 2. Store previous node call is as previous 3. Assign previous->next to temp->next 4. In this case, the temp->next will be Null so no difference from deletion at middle 5. Free(temp)
  • 36. Deletion Description 4 17 head 42 6 4 17 head 42 6 4 17 6 head
  • 37. 3(b).Function to delete an element at the rear end void delete_rear() { if(head = = NULL) // no node { printf("list is emptyn"); } if(head ->next = = NULL) // only one node { head=NULL; free(head); } else { temp = head; while(temp->next != NULL) } { ptr1 = temp; temp = temp ->next; } ptr1->next = NULL; free(temp); } } Department of ISE Acharya Institute of Technology struct node { int data; struct node *next; } struct node *head, *temp, *ptr1;
  • 38. Department of ISE 3(c).Function to delete a node from a specified location is given void delete_specloc( ) { if(head = = NULL) // empty list { printf("the list is emptyn"); } else temp=head; Acharya Institute of T}echnology for(i=1;i<loc;i++) { ptr1=temp; temp=temp->next; } ptr1->next=temp->next; free(temp); }
  • 39. Function to display/Traverse the contents of the list void display( ) { if(head = = NULL) { printf("the list is emptyn"); } else { temp = head; printf("the contents of the list are:n"); while(temp!= NULL) { printf("%d",temp->data); temp= temp->next; } }} Department of ISE Acharya Institute of Technology
  • 40. Note: 1.To implement stacks using linked lists the functions required are •Insert_front( ), Delete_front and Display( ) OR •Insert_rear( ), Delete_rear and Display( ) 2.To implement queues using linked lists the function required are •Insert_front( ), Delete_rear and Display( ) OR •Insert_rear( ), Delete_front and Display( ) 3.To implement De-queues using linked lists the function required are Insert_front( ), Delete_front, Insert_rear( ), Delete_rear and Display( ) Department of ISE Acharya Institute of Technology
  • 41. Other operations of a linked list •Function to count the number of nodes in a list int countnodes( ) { int count = 0; temp= head; while(temp!= NULL) { count = count + 1; temp = temp->next; } return count; } Department of ISE Acharya Institute of Technology
  • 42. • Function to concatenate 2 lists int concatenate( ) { if(firsthead = = NULL) return secondhead; if(secondhead = = NULL) return firsthead; temp = firsthead; while(temp->next!= NULL) { temp = temp->next; } temp->next = secondhead; } Department of ISE Acharya Institute of Technology
  • 43. Function to search for an item in the list and display the position if found void search_item( ) { int pos; if(head= = NULL) { printf(“list is emptyn”); return; } temp = head; pos = 1; while(temp != NULL && item ! =temp->data) { temp = temp->next; pos = pos + 1; } if(temp = = NULL) { printf(“Unsuccessful searchn”); return; } printf(“Successful search and item found at position %dn”, pos); } Department of ISE Acharya Institute of Technology
  • 44. Disadvantages of Singly Linked List •Given the address of a node in the list, it is difficult to find the address of previous node. •Traversing of list is possible only in the forward direction and hence singly linked list is also termed as one-way list. Doubly Linked List Representation To increase the performance and efficiency of algorithms, it is required to traverse the list in either forward or backward direction. Therefore a two-way list called as doubly linked list can be made use of, so that traversing from left to right (forward) or right to left (backward) is possible. Department of ISE Acharya Institute of Technology
  • 45. DOUBLY LINKED LIST Doubly linked lists Each node points to not only successor but the predecessor There are two NULL: at the first and last nodes in the list  It is a way of going both directions in a linked list, forward and reverse.  Many applications require a quick access to the predecessor node of some node in list. A Head B  C 
  • 46. Advantages over Singly-linked Lists Quick update operations: such as: insertions, deletions at both ends (head and tail), and also at the middle of the list. A node in a doubly-linked list store two references: •A next link; that points to the next node in the list, and •A prev link; that points to the previous node in the list.
  • 47. REPRESENTATION OF A NODE IN DOUBLY LINKED LIST struct Node { struct Node *prev; int data; struct Node *next; } * head;
  • 48. Each node in the list consists of •prev – Contains the address of the left node or previous node •data – It is the data to be processed. •next – Contains the address of the right node or next node The structure declaration for each node is as shown below struct node { int data; struct node *prev; struct node *next; }; Department of ISE Acharya Institute of Technology
  • 49. In a singly linked list, we could traverse only in one direction, because each node contains address of the next node and it doesn't have any record of its previous nodes. However, doubly linked list overcome this limitation of singly linked list. Due to the fact that, each node of the list contains the address of its previous node, we can find all the details about the previous node as well by using the previous address stored inside the previous part of each node.
  • 50. Memory Representation of a doubly linked list
  • 51. Operations on doubly linked list  Node Creation (single node)  Insertion at the beginning  Insertion at the end  Insertion after a specified location  Deletion from beginning  Deletion from end  Deletion from a specified location  Traversal  searching
  • 52. Node Creation struct node { struct node *prev; int data; struct node *next; }; struct node *head;
  • 53. Function to insert an element at the front end of DLL: void insertfront ( ) { newnode=(struct node*)malloc(sizeof(struct node)); newnode ->data = item; newnode ->prev = NULL; newnode->next = NULL; if(head = = NULL) return newnode; newnode ->next = head; head->prev = newnode; head=newnode; return newnode; } Department of ISE Acharya Institute of Technology struct node { struct node *prev; int data; struct node *next; } * head,*newnode;
  • 54.
  • 55. Function to insert an element at the rear end void insertrear( ) { newnode = (struct node*)malloc(sizeof(struct node)); newnode ->data = item; newnode ->prev=NULL; newnode ->next = NULL; if(head = = NULL) return newnode ; temp= head; while(temp->next != NULL) { temp = temp->next; } temp->next = newnode ; newnode ->prev = temp; } Department of ISE Acharya Institute of Technology
  • 56. Insertion in doubly linked list after Specified node
  • 57. Int insert_specified ( ) { newnode= (struct node *)malloc(sizeof(struct node)); newnode->next=NULL; Newnode->prev=NULL; int i, loc; if(head == NULL) { return newnode; } else { printf("nEnter the locationn"); scanf("%d",&loc); ptr=head; for(i=1;i<loc;i++) { ptr = ptr->next; } newnode->data = item; newnode->next = ptr->next; newnode-> prev = ptr; ptr->next->prev=newnode; ptr->next = newnode; printf("Node Insertedn"); } }
  • 58. DELETION IN DOUBLY LINKED LIST
  • 59. 10 20 30 200 300 300 200 100 NULL temp=head NUL L temp = head; head = head -> next; head -> prev = NULL; free(temp); head NUL L 200
  • 60. void beginning_delete() { if(head == NULL) { printf("n List is empty”); } else if(head->next == NULL) { head = NULL; free(head); printf("nNode Deletedn"); } else { temp = head; head = head -> next; head -> prev = NULL; free(temp); printf("nNode Deletedn"); } } DELETION AT THE BEGINNING
  • 61.  Deletion of the last node in a doubly linked list needs traversing the list in order to reach the last node of the list and then make pointer adjustments at that position.  In order to delete the last node of the list, we need to follow the following steps. •If the list is already empty then the condition head == NULL will become true and therefore the operation can not be carried on. •If there is only one node in the list then the condition head → next == NULL become true. In this case, we just need to assign the head of the list to NULL and free head in order to completely delete the list DELETION AT THE END
  • 62. 10 20 30 200 NUL L 300 200 100 NULL ptr=head NUL L ptr -> prev -> next = NULL; free(ptr); ptr 100 200
  • 63. void last_delete() { if(head == NULL) { printf("n UNDERFLOWn"); } else if(head->next == NULL) { head = NULL; free(head); } DELETION AT THE END else { ptr = head; if(ptr->next != NULL) { ptr = ptr -> next; } ptr -> prev -> next = NULL; free(ptr); } }
  • 64. DELETION OF NODE FROM A SPECIFIED POSITION IN DLL:
  • 66.  Suppose you want to delete the second node from the list.  Start traversing the linked list from the head until the position = 2 of the node to be deleted.  Let the node at the position 2 of the list be temp.  Assign the next pointer of temp to temp's previous node's next pointer.  Assign the temp's prev pointer to temp's next node's prev pointer.  Delete the temp node.
  • 67. void delete_given_position( ) { int i; temp = head; for(i=1; i<position && temp!=NULL; i++) { temp = temp->next; } if(temp != NULL) { temp->prev->next = temp->next; temp->next->prev = temp->prev; free(temp); } else { printf("Invalid position!n"); }}
  • 68. Function to Traverse /display the contents of the list void display( ) { if(head = = NULL) { printf("the list is emptyn"); return; } printf("the contents of the list are:n"); temp = head; while(temp != NULL) { printf("%dn",temp->data); temp= temp->next;} } Department of ISE Acharya Institute of Technology
  • 69. Function to search for an item in the DLL and display the position if found void search_item( ) { int pos; if(head= = NULL) { printf(“list is emptyn”); return; } temp = head; pos = 1; while(temp != NULL && item ! =temp->data) { temp = temp->next; pos = pos + 1; } if(temp = = NULL) { printf(“Unsuccessful searchn”); return; } printf(“Successful search and item found at position %dn”, pos); } Department of ISE Acharya Institute of Technology
  • 70. Circular linked list 1. Circular singly linked list 2. Circular doubly linked list
  • 71. 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 can have circular singly linked list as well as circular doubly linked list. • We traverse a circular singly linked list until we reach the same node where we started. • The circular singly liked list has no beginning and no ending. • There is no null value present in the next part of any of the nodes. • The following image shows a circular singly linked list.
  • 72.
  • 73. Circular singly linked list  Circular linked list are mostly used in task maintenance in operating systems.  There are many examples where circular linked list are being used in computer science including browser surfing where a record of pages visited in the past by the user, is maintained in the form of circular linked lists and can be accessed again on clicking the previous button.
  • 74. Circular Singly Linked List In normal singly linked list, •The link part of the last node has NULL value, specifying that it is the last node. •Given the address of any node ‘x’, it is only possible to reach the nodes which follow ‘x’ and it is not possible to reach the nodes that precedes ‘x’ (previous nodes). To reach the nodes that precedes ‘x’, it is required to preserve a pointer variable first, which contains the address of the first node in the list and use this for traversing. •Also, given the address of the first node to get the address of the last node, the list has to be traversed from the beginning till the last node is reached. Department of ISE Acharya Institute of Technology
  • 75. These disadvantages can be overcome using circular singly linked list. In a circular singly linked list the link field of the last node points to the first node in the list, which makes the list a circular one. The pictorial representation is as shown below. Department of ISE Acharya Institute of Technology
  • 76. OPERATIONS OF CIRCULAR SINGLY LINKED LIST(CSLL): Department of ISE Acharya Institute of Technology  NODE CREATION  INSERTION  DELETION  TRAVERSING/DISPLAY  SEARCHING
  • 77. NODE CREATION: •Here the link field of the last node contains address of the first node. •In the following functions we use the structure definition as shown below. struct node { int data; struct node *next; }*head; Department of ISE Acharya Institute of Technology
  • 79. 20 300 10 200 300 200 temp->next = newnode; newnode->next = head; return last; temp 30 200 600 600 head head Insertion into circular singly linked list at beginning
  • 80. void beg_insert(int item) { newnode= (struct node *)malloc(sizeof(struct n ode)); newnode-> data = item; if(head == NULL) //no nodes exist { head = newnode; newnode -> next = head; } else { temp = head; while(temp->next != head) { temp = temp->next; } newnode->next = head; temp -> next = newnode; head = newnode; } } Insertion into circular singly linked list at beginning
  • 81. Function to insert an element at the rear end- CSLL Department of ISE Acharya Institute of Technology void lastinsert( ) { newnode = (struct node *)malloc(sizeof(struct nod e)); newnode->data = item; if(head == NULL) { head = newnode; newnode-> next = head; } else { temp = head; while(temp -> next != head) { temp = temp -> next; } temp -> next = newnode; newnode -> next = head; } }
  • 82.
  • 83. Function to insert an item at a specified position(after a specified node) - CSLL void insert_pos( ) { newnode=(struct node)malloc(sizeof(struct node)); newnode ->data = item; temp=head; if(head = = NULL && loc = = 1)// no elements in the list head=newnode; Newnode->next=head } Department of ISE Acharya Institute of Technology else { for(i=1;i<loc;i++) { temp = temp->next; } newnode ->next =temp->next; temp ->next = newnode; } }
  • 84. Deletion from circular singly linked list at beginning: void beg_delete() { if(head == NULL) { printf("nUNDERFLOWn"); } else if(head->next == head) // 1 node { head = NULL; free(head); printf("nNode Deletedn"); } else { ptr = head; while(ptr -> next != head) { ptr = ptr -> next; } ptr->next = head->next; free(head); head = ptr->next; printf("nNode Deletedn"); } }
  • 85. Deletion from circular singly linked list at END: void last_delete() { if(head==NULL) { printf("nUNDERFLOWn"); } else if (head ->next == head) { head = NULL; free(head); printf("nNode Deletedn"); } else { ptr = head; while(ptr ->next != head) { preptr=ptr; ptr = ptr->next; } preptr->next = ptr -> next; free(ptr); printf("nNode Deletedn"); } }
  • 86. Function to display/Traverse the contents of the list IN CSLL void display( ) { if(head = = NULL) { printf("the list is emptyn"); } else { temp = head; printf("the contents of the list are:n"); while(temp!= head) { printf("%d",temp->data); temp= temp->next; } }} Department of ISE Acharya Institute of Technology
  • 87. Function to search for an item in the CSLL and display the position if found void search_item( ) { int pos; if(head= = NULL) { printf(“list is emptyn”); return; } temp = head; pos = 1; while(temp ->next != head && item ! =temp->data) { temp = temp->next; pos = pos + 1; } if(temp->next = = head) { printf(“Unsuccessful searchn”); return; } printf(“Successful search and item found at position %dn”, pos); } Department of ISE Acharya Institute of Technology
  • 88. Circular Doubly Linked List -CDLL Department of ISE Acharya Institute of Technology
  • 89. OPERATIONS:  NODE CREATION  INSERTION  DELETION  TRAVERSING/DISPLAY  SEARCHING
  • 90. NODE CREATION: struct node { int data; struct node *next; struct node *prev; } *head; Department of ISE Acharya Institute of Technology
  • 91. void beg_insert( ) { newnode = (struct node *)malloc(sizeof(struct node)); newnode ->data=item; if(head==NULL) { head = newnode; newnode -> next = head; newnode -> prev = head; } else { temp = head; while(temp -> next != head) { temp = temp -> next; } temp -> next = newnode; newnode -> prev = temp; head -> prev = newnode; newnode -> next = head; head = newnode; } printf("Node Inserted"); } } Insertion into circular doubly linked list at beginning
  • 92. Insertion into circular doubly linked list at END void insertion_last( ) { newnode = (struct node *) malloc(sizeof(struct node)); newnode ->data=item; if(head == NULL) { head = newnode; newnode -> next = head; newnode -> prev = head; } else { temp = head; while(temp->next !=head) { temp = temp->next; } temp->next = newnode; newnode ->prev=temp; head -> prev = newnode; newnode -> next = head; } } printf("nNode Insertedn"); }
  • 93. Deletion from circular doubly linked list -Beginning void deletion_beginning() { if(head == NULL) { printf("n UNDERFLOWn"); } else if(head->next == head) { head = NULL; free(head); } else { temp = head; while(temp -> next != head) { temp = temp -> next; } temp -> next = head -> next; head -> next -> prev = temp; free(head); head = temp -> next; } }
  • 94. Deletion from circular doubly linked list -END void deletion_last() { if(head == NULL) { printf("n UNDERFLOWn"); } else if(head->next == head) { head = NULL; free(head); } else { temp= head; while(temp >next != head) { temp = temp -> next; } temp -> prev -> next = head; head -> prev = temp -> prev; free(temp); } }
  • 95. Linked list implementation of stack  Instead of using array, we can also use linked list to implement stack. Linked list allocates the memory dynamically. However, time complexity in both the scenario is same for all the operations i.e. push, pop and peek.  In linked list implementation of stack, the nodes are maintained non-contiguously in the memory. Each node contains a pointer to its immediate successor node in the stack. Stack is said to be overflow if the space left in the memory heap is not enough to create a node.
  • 97. Adding a node/element to the stack (Push operation) Algorithm Step 1 - Create a newNode with given value. Step 2 - Check whether stack is Empty (top == NULL) Step 3 - If it is Empty, then set newNode → next = NULL. Step 4 - If it is Not Empty, then set newNode → next = top. Step 5 - Finally, set top = newNode. Time Complexity : o(1)
  • 98.
  • 99. void push () { newnode =(struct node*)malloc(sizeof(struct node)); { printf("Enter the value"); scanf("%d",&val); if(top==NULL) //no elements in stack { newnode->data= item; newnode-> next = NULL; top=newnode; } else { newnode->data = item; newnode->next = top; top=newnode; } printf("Item pushed"); } } struct node { int data; struct node *next; } *top;
  • 100. Deleting a node/element from the stack (POP operation) Algorithm: Step 1 - Check whether stack is Empty (top == NULL). Step 2 - If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!" and terminate the function Step 3 - If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'. Step 4 – Decrement top. Step 5 - Finally, delete 'temp'. (free(temp)). Time Complexity : o(n)
  • 101.
  • 102. void pop() { int item; if (top == NULL) { printf("Underflow"); } else { item = top->data; temp= top; top = top->next; free(temp); } }
  • 103. Display the nodes (Traversing)  Displaying all the nodes of a stack needs traversing all the nodes of the linked list organized in the form of stack. For this purpose, we need to follow the following steps.  Copy the head pointer into a temporary pointer.  Move the temporary pointer through all the nodes of the list and print the value field attached to every node. Time Complexity : o(n)
  • 104. void display() { ptr=top; if(ptr == NULL) { printf("Stack is emptyn"); } else { printf("Printing Stack elements n"); while(ptr!=NULL) { printf("%dn",ptr->val); ptr = ptr->next; } } }
  • 105. Queue implementation Using Linked List  Queue using an array is not suitable when we don't know the size of data which we are going to use.  A queue data structure can be implemented using a linked list data structure.  The queue which is implemented using a linked list can work for an unlimited number of values.  In linked list implementation of a queue, the last inserted node is always pointed by 'rear' and the first node is always pointed by 'front'.
  • 106.
  • 107. enQueue(value) - Inserting an element into the Queue Step 1: Allocate the space for the new node PTR Step 2: SET PTR -> DATA = VAL Step 3: IF FRONT = NULL SET FRONT = REAR = PTR SET FRONT -> NEXT = REAR -> NEXT = NULL ELSE SET REAR -> NEXT = PTR SET REAR = PTR SET REAR -> NEXT = NULL [END OF IF] Step 4: END
  • 108. void enqueue( ) { ptr = (struct node *) malloc (sizeof(struct no de)); ptr -> data = item; if(front == NULL) { front = ptr; rear = ptr; rear -> next = NULL; } else { rear -> next = ptr; rear = ptr; rear->next = NULL; } } }
  • 109. deQueue() - Deleting an Element from Queue Step 1: IF FRONT = NULL Write " Underflow " Go to Step 5 [END OF IF] Step 2: SET PTR = FRONT Step 3: SET FRONT = FRONT -> NEXT Step 4: FREE PTR Step 5: END
  • 110. void delete (struct node *ptr) { if(front == NULL) { printf("nUNDERFLOWn"); } else { ptr = front; front = front -> next; free(ptr); } }
  • 112. Polynomial – Using Singly Linked List Representation Consider the polynomial 9x3 + 7x2 + 6x + 9. This polynomial can be represented using a singly linked list as shown below. Every node has 3 fields cf – coefficient field px – power of x next – contains the address of next node. Department of ISE Acharya Institute of Technology
  • 113. Polynomial Representation using Linked List A Polynomial has mainly two fields. exponent and coefficient. Node of a Polynomial: For example 3x^2 + 5x + 7 will represent as follows. In each node the exponent field will store the corresponding exponent and the coefficient field will store the corresponding coefficient. Link field points to the next item in the polynomial.
  • 114. 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  other is the exponent
  • 115. • The sign of each coefficient and exponent is stored within the coefficient and the exponent itself • Additional terms having equal exponent is possible one • The storage allocation for each term in the polynomial must be done in ascending and descending order of their exponent
  • 116. Therefore, the structure declaration to represent this node will be struct polynode { int cf; int px; struct polynode *next; }*head; Department of ISE Acharya Institute of Technology
  • 117. ADDITION OF 2 POLYNOMIALS
  • 118. Input: 1st number = 5x^2 + 4x^1 + 2x^0 2nd number = 5x^1 + 5x^0 Output: 5x^2 + 9x^1 + 7x^0
  • 119. Algorithm: Step 1: Compare the exponent of P and the corresponding exponent of q. Step 2:if expo(p) < expo(q) added the terms pointer to q to the resultant list and now advanced the q pointer. Step 3:expo(p) > expo(q) added the terms pointer to p to the resultant list and now advanced the p pointer. Step 3:If expo(p) = expo(q) Add the coefficients of these two terms and link this to the resultant list and advance the pointers p and q to their next nodes. Step 4:If there is no node in the second polynomial to compare with, so the last node in the first polynomial is added to the end of the resultant linked list. Step 5:If there is no node in the first polynomial to compare with, so the last node in the second polynomial is added to the end of the resultant linked list.
  • 120. Example: p= 30x2 + 20x + 100 —————(1) Q= 60x3 + 50x2 + 60x——————(2) Case1:expo(p) < expo(q)
  • 121. Case2: expo(p) = expo(q)
  • 122.
  • 123.
  • 124. In the above figure, you will notice that there is no node in the second polynomial to compare with. you can understand in a better way after seeing the figure, so the last node in the first polynomial is added to the end of the resultant linked list. The next below figure is the output which comes Polynomials Addition of two polynomials.
  • 126. Note: link field of last node contains the address of head and link field of header node points to the first node of the list. Every node has 3 fields •cf – coefficient field •px – power of x •link – contains the address of next node. Therefore, the structure declaration to represent this node will be struct node { int cf; int px; struct node *link; }; typedef struct node* NODE; Program to add two Polynomials using Circular Singly Linked List header node Department of ISE Acharya Institute of Technology
  • 127. void sum() { node=(struct node*)malloc(sizeof(struct node)); head3=node; ptr1=head1; ptr2=head2; while(ptr1!=NULL && ptr2!=NULL) { ptr=node; if (ptr1->pow < ptr2->pow ) s { node->coff=ptr2->coff; node->pow=ptr2->pow; ptr2=ptr2->next; } function to add 2 polynomials:
  • 128. else if ( ptr1->pow > ptr2->pow ) { node->coff=ptr1->coff; node->pow=ptr1->pow; ptr1=ptr1->next; } else // ptr1->pow == ptr2->pow { node->coff=ptr2->coff+ptr1->coff; node->pow=ptr2->pow; ptr1=ptr1->next; ptr2=ptr2->next; } } if (ptr1==NULL) { while(ptr2!=NULL)
  • 129. { node->coff=ptr2->coff; node->pow=ptr2->pow; ptr2=ptr2->next; } } else if (ptr2==NULL) { while(ptr1!=NULL) { node->coff=ptr1->coff; node->pow=ptr1->pow; ptr1=ptr1->next; } }}
  • 130. Sparse matrix-Linked List Representation In linked list representation, linked list data structure is used to represent a sparse matrix. In linked list representation, each node consists of four fields whereas, in array representation, there are three fields, i.e., row, column, and value. The following are the fields in the linked list: •Row: It is an index of row where a non-zero element is located. •Column: It is an index of column where a non-zero element is located. •Value: It is the value of the non-zero element which is located at the index (row, column). •Next node: It stores the address of the next node.
  • 131.  In the above figure, sparse represented in the linked list form. In the node, first field represents the index of row, second field represents the index of column, third field represents the value and fourth field contains the address of the next node.