0% found this document useful (0 votes)
11 views79 pages

Unit 4-5 Linked List

The document provides an overview of lists and linked lists, detailing their definitions, implementations, and operations. It explains contiguous lists using arrays and linked lists, which consist of nodes with data and pointers, allowing dynamic memory allocation. Additionally, it covers various operations such as insertion, deletion, and traversal in singly linked lists, along with algorithms and C functions for these operations.
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)
11 views79 pages

Unit 4-5 Linked List

The document provides an overview of lists and linked lists, detailing their definitions, implementations, and operations. It explains contiguous lists using arrays and linked lists, which consist of nodes with data and pointers, allowing dynamic memory allocation. Additionally, it covers various operations such as insertion, deletion, and traversal in singly linked lists, along with algorithms and C functions for these operations.
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/ 79

List and Linked List

Prepared by Kriti Nemkul 1


Introduction to List and Linked Lists
• List is a term used to refer to a linear collection of data items. A list
can be implemented either by using arrays or linked list.
• Usually, a large block of memory is occupied by an array which may
not be in use and it is difficult to increase the size of an array.
• Another way of storing a list is to have each element in a list contain
field called a link or pointer, which contains the address of the next
element in the list.
• The successive elements in the list need not to occupy adjacent space
in memory. This type of data structure is called a linked list.

Prepared by Kriti Nemkul 2


List
• A list is a set of items organized sequentially. For example, an array is
a list where the sequential organization is provided implicitly by its
index.
• We can represent a list in two ways:
Contiguous List
Linked List

Prepared by Kriti Nemkul 3


Contiguous List
• A contiguous list is a list in array implementation.
• In this representation, each item is contiguous to next item.
• The operations of insertion and deletion of items can be done
to/from anywhere within the list.

Prepared by Kriti Nemkul 4


Implementation of Contiguous List
• To implement a contiguous list, we need
to define a large enough array to hold all
the items of the list.
• The first item of the list is placed at 0th
position of array and successive items in
successive positions of the array.
• The last item of the list is indicated by
“last_index”. For example, in the figure
last_index=7.

Prepared by Kriti Nemkul 5


Implementation of Contiguous List…
Assumptions
• MAXLIST is defined.
• CList[MAXLIST] is defined as an array to hold the items of the list.
• last_index is defined to indicate index the last element.
• Initially, last_index=-1.

Prepared by Kriti Nemkul 6


Implementation of Contiguous List…
Insertion
1. Read item x to insert.
2. If last_index==MAXLIST- 1, declare list full and return.
3. If last_index== -1, increment last_index and perform Clist[0]=x and
return.
4. Read position pos to insert (pos=0 means CList[0]).
5. If pos>last_index+1, declare invalid and return.
6. i=last_index;
7. while(i>=pos)
CList[i+1]=CList[i];
i=i-1;
8. Clist[pos]=x;
9. Increment last_index
10. Return

Prepared by Kriti Nemkul 7


Implementation of Contiguous List…
Deletion
1. If last_index==-1, declare list empty and return.
2. Read position pos to delete.
3. If pos>last_index, declare invalid and return.
4. x=CList[pos];
5. i=pos;
6. while(i<last_index)
CList[i]=CList[i+1];
i=i+1;
7. Decrement last_index
8. Return x as deleted item

Prepared by Kriti Nemkul 8


Self Referential structure

Prepared by Kriti Nemkul 13


Linked List
• A linked list is a collection of nodes, where nodes are connected to each
other and each node consists of two parts:
info: the actual element to be stored in the list. It is also called data field.
link: one or two links that points to next and previous node in the list. It is
also called next or pointer field. It contains the address of the next node in the
list. The address of the last node of a linked list is NULL.
• The nodes in a linked list are not stored contiguously in the memory
• You don't have to shift any element in the list.
• Memory for each node can be allocated dynamically whenever the need
arises.
• The size of a linked list can grow or shrink dynamically

Prepared by Kriti Nemkul 14


Operation in Linked List
The basic operations to be performed on the linked list are as follows:
• Creation: This operation is used to create a linked list
• Insertion: This operation is used to insert a new nose in a kinked list in an specified position. A new node
may be inserted
✔At the beginning of the linked list
✔ At the end of the linked list
✔At he specified position in a linked list
• Deletion: The deletion operation is used to delete a node from the linked list. A node may be deleted from
✔The beginning of the linked list
✔the end of the linked list
✔ the specified position in the linked list.
• Traversing: The list traversing is a process of going through all the nodes of them linked list from on end to
the other end. The traversing may be either forward or backward.
• Searching or find: This operation is used to find an element in a linked list. In the desired element is found
then we say operation is successful otherwise unsuccessful.
• Concatenation: It is the process of appending second list to the end of the first list.

Prepared by Kriti Nemkul 15


Types of Linked List
1. Singly Linked List.
2. Doubly Linked List.
3. Circular Linked List.
4. Circular Doubly Linked List.

Prepared by Kriti Nemkul 16


Singly Linked List (Linear Linked List)
• A singly linked list is a dynamic data structure which may grow or
shrink, and growing and shrinking depends on the operation made.
• In this type of linked list each node contains two fields one is info field
which is used to store the data items and another is link field that is
used to point the next node in the list.
• The last node has a NULL pointer.
• The following example is a singly linked list that contains three
elements 5, 3, 8.

Prepared by Kriti Nemkul 17


Representation of singly linked list:
• We can create a structure for the singly linked list the each node has two
members, one is info that is used to store the data items and another is next
field that store the address of next node in the list.
• We can define a node as follows:
struct Node
{
int info;
struct Node *next;
};
typedef struct Node NodeType;
NodeType *head; //head is a pointer type structure variable
This type of structure is called self-referential structure.
The NULL value of the next field of the linked list indicates the last node and we define
macro for NULL and set it to 0 as below:
#define NULL 0

Prepared by Kriti Nemkul 18


Creating a Node:
• To create a new node, we use the malloc function to dynamically
allocate memory for the new node.
• After creating the node, we can store the new item in the node using a
pointer to that nose.
• The following steps clearly shows the steps required to create a node
and storing an item.

Prepared by Kriti Nemkul 19


The getNode function
• we can define a function getNode() to allocate the memory for a node
dynamically. It is user-defined function that return a pointer to the
newly created node.
Nodetype *getNode()
{
NodeType *p;
p==(NodeType*)malloc(sizeof(NodeType));
return(p);
}

Prepared by Kriti Nemkul 20


Creating the empty list
void createEmptyList(NodeType *head)
{
head=NULL;
}

Prepared by Kriti Nemkul 21


Inserting Nodes

Whenever startnode==NULL, the linked list isempty.


Insertion: For insertion, we need to do the following three things:
1. Allocating a node: This can be done as,
struct linkedlist *node;
node=(struct linkedlist *)malloc(sizeof(struct linkedlist));
2. Assigning the data: This can be done as,
node->info=x;
3. Adjusting the pointers: This depends on where we want to insert
the node in the linked list. There are three options available:
I. Insert at Beginning
II. Insert at End
III. Insert after any position

Prepared by Kriti Nemkul 22


An algorithm to insert a node at the beginning of
the singly linked list:
let *head be the pointer to first node in the current list
1. Create a new node using malloc function
NewNode=(NodeType*)malloc(sizeof(NodeType));
2. Assign data to the info field of new node
NewNode->info=newItem;
3. Set next of new node to head
NewNode->next=head;
4. Set the head pointer to the new node
head=NewNode;
5. End
Prepared by Kriti Nemkul 23
C function to insert a node at the beginning of the singly
linked list:
I. Insert a t Beginning
void InsertAtBeg(int newItem)
{
NodeType *NewNode;
NewNode=getNode();
NewNode->info=newItem;
NewNode->next=head;
head=NewNode;
}

Prepared by Kriti Nemkul 24


An algorithm to insert a node at the end of the
singly linked list:
let *head be the pointer to first node in the current list
1. Create a new node using malloc function
NewNode=(NodeType*)malloc(sizeof(NodeType));
2. Assign data to the info field of new node
NewNode->info=newItem;
3. Set next of new node to NULL
NewNode->next=NULL;
4. if (head ==NULL)then
Set head =NewNode.and exit.
5. Set temp=head;
6 while(temp->next!=NULL)
temp=temp->next; //increment temp
7. Set temp->next=NewNode;
8. End
Prepared by Kriti Nemkul 25
The C function to insert a node at the end of the linked list:
II. Insert a t End
void InsertAtEnd(int newItem){
NodeType *NewNode;
NewNode=getNode();
NewNode->info=newItem;
NewNode->next=NULL;
if(head==NULL){
head=NewNode;
}
else{
temp=head;
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=NewNode;}}
Prepared by Kriti Nemkul 26
An algorithm to insert a node after the given node
in singly linked list:
let *head be the pointer to first node in the current list and *p be the
pointer to the node after which we want to insert a new node.
1. Create a new node using malloc function
NewNode=(NodeType*)malloc(sizeof(NodeType));
2. Assign data to the info field of new node
NewNode->info=newItem;
3. Set next of new node to next of p
NewNode->next=p->next;
4. Set next of p to NewNode
p->next =NewNode..
5. End

Prepared by Kriti Nemkul 27


The C function to insert a node after the given
node in singly linked list:
void InsertAfterNode(NodeType *p int newItem)
{
NodeType *NewNode;
NewNode=getNode();
NewNode->info=newItem;
if(p==NULL)
{
printf(“Void insertion”);
exit(1);
}
else
{
NewNode->next=p->next;
p->next =NewNode..
}
}

Prepared by Kriti Nemkul 28


An algorithm to insert a node at the specified
position in a singly linked list:
let *head be the pointer to first node in the current list
1. Create a new node using malloc function
NewNode=(NodeType*)malloc(sizeof(NodeType));
2. Assign data to the info field of new node
NewNode->info=newItem;
3. Enter position of a node at which you want to insert a new node. Let this
position is pos.
4. Set temp=head;
5. if (head ==NULL)then
printf(“void insertion”); and exit(1).
6. for(i=1; i<pos-1; i++)
temp=temp->next;
7. Set NewNode->next=temp->next;
set temp->next =NewNode..
8. End

Prepared by Kriti Nemkul 29


The C function to insert a node at the specified
position in a singly linked list:
void InsertAtPos(int newItem) for(i=1; i<pos-1; i++)
{ {
NodeType *NewNode; temp=temp->next;
int pos , i ; }
printf(“ Enter position of a node at NewNode=getNode();
which you want to insert a new NewNode->info=newItem;
node”); NewNode->next=temp->next;
scanf(“%d”,&pos); temp->next =NewNode;
if(head==NULL) }
{ }
printf(“void insertion”);
exit(1).
}
else
{
temp=head;

Prepared by Kriti Nemkul 30


Deleting Nodes
A node may be deleted:
From the beginning of the linked list
from the end of the linked list
from the specified position in a linked list

Prepared by Kriti Nemkul 31


An algorithm to deleting the first node of the
singly linked list:
let *head be the pointer to first node in the current list
1. If(head==NULL) then
print “Void deletion” and exit
2. Store the address of first node in a temporary variable temp.
temp=head;
3. Set head to next of head.
head=head->next;
4. Free the memory reserved by temp variable.
free(temp);
5. End

Prepared by Kriti Nemkul 32


The C function to deleting the first node of the
singly linked list:
void deleteBeg()
{
NodeType *temp;
if(head==NULL)
{
printf(“Empty list”);
exit(1).
}
else
{
temp=head;
printf(“Deleted item is %d” , head->info);
head=head->next;
free(temp);
}
}

Prepared by Kriti Nemkul 33


Deleting the last node of the linked list:
An algorithm to deleting the last node of the singly linked list:
let *head be the pointer to first node in the current list
1. If(head==NULL) then //if list is empty
print “Void deletion” and exit
2. else if(head->next==NULL) then //if list has only one node
Set temp=head;
print deleted item as,
printf(“%d” ,head->info);
head=NULL;
free(temp);
3. else
set temp=head;
while(temp->next->next!=NULL)
set temp=temp->next;
End of while
free(temp->next);
Set temp->next=NULL;
4. End
Prepared by Kriti Nemkul 34
The C function to deleting the last node of the
singly linked list:
let *head be the pointer to first node in the else
current list {
void deleteEnd() temp=head;
{
NodeType *temp; while(temp->next->next!=NULL)
if(head==NULL) {
{ temp=temp->next;
printf(“Empty list”); }
return; printf(“deleted item is %d'” , temp-
}
else if(head->next==NULL) >next->info):
{ free(temp->next);
temp=head; temp->next=NULL;
head=NULL; }
printf(“Deleted item is %d”, temp->info); }
free(temp);
}

Prepared by Kriti Nemkul 35


An algorithm to delete a node after the given node
in singly linked list:
let *head be the pointer to first node in the current list
and *p be the pointer to the node
after which we want to delete a new node.
1. if(p==NULL or p->next==NULL) then
print “deletion not possible and exit
2. set q=p->next
3. Set p->next=q->next;
4. free(q)

Prepared by Kriti Nemkul 36


The C function to delete a node after the given
node in singly linked list:
let *p be the pointer to the node after which we want to delete a new node.
void deleteAfterNode(NodeType *p)
{
NodeType *q;
if(p==NULL || p->next==NULL )
{
printf(“Void insertion”);
exit(1);
}
else
{
q=p->next;
p->next=q->next;
free(q);
}
}

Prepared by Kriti Nemkul 37


An algorithm to delete a node at the specified
position in a singly linked list:
let *head be the pointer to first node in the current list
1. Read position of a node which to be deleted, let it be pos.
2. if head==NULL
print “void deletion” and exit
3. Enter position of a node at which you want to delete a new node. Let this position is pos.
4. Set temp=head
declare a pointer of a structure let it be *p
5. if (head ==NULL)then
print “void ideletion” and exit
otherwise;.
6. for(i=1; i<pos-1; i++)
temp=temp->next;
7. print deleted item is temp->next->info
8. Set p=temp->next;
9. Set temp->next =temp->next->next;
10. free(p);
11. End

Prepared by Kriti Nemkul 38


The C function to delete a node at the specified
position in a singly linked list
void deleteAtSpecificPos() temp=head;
{ for(i=1; i<pos-1; i++)
NodeType *temp *p;
int pos, i;
{
if(head==NULL) temp=temp->next;
{ }
printf(“Empty list”); p=temp->next;
return; ` printf(“Deleted item is %d”, p-
} >info);
else temp->next =p->next;
{
printf(“Enter position of a node which free(p);
you wand to delete”); }
scanf(“%d” , &pos); }

Prepared by Kriti Nemkul 39


Searching an item in a linked list:
• To search an item from a given linked list we need while(temp!=NULL)
to find the node that contain this data item.
If we find such a node then searching is successful {
otherwise searching unsuccessful. if(temp->info==key)
let *head be the pointer to first node in the current {
list
void searchItem() printf(“Search successful”);
{ break;
NodeType *temp; }
int key;
if(head==NULL) temp=temp->next;
{ }
printf(“empty list”); if(temp==NULL)
exit(1);
} printf(“Unsuccessful search”);
else }
{
printf(“Enter searched item”); }
scanf('%d” ,&key);
temp=head;

Prepared by Kriti Nemkul 40


practise Question
Explain the advantages and disadvantages of representing a
group of items as an array versus a linear linked list with suitable
examples.

Answer: Memory (RAM) is one of the most important resource of a computer. It must be utilized
efficiently.
When we represent a group of items as an array, then memory for all these items are allocated at
compile time in contiguous memory locations and is fixed. This process is also called static memory
allocation and the list so formed is called contiguous list. [Give structure of contiguous list and
the process of insertion and deletion of items]
The disadvantages with this approachare:
It is actually quite difficult to know the exact size of the array in advance (prior to execution).
If the size needed at run time is small than the specified size, then we will have
wastage of memory space.
If the size needed at run time is greater than the specified size, then we will have
shortage of memory space.
Insertion and deletion of items is difficult in this representation.

Prepared by Kriti Nemkul 49


49
However, the following are the advantages of array
representation of a group of items:
It is quite easy to access any item within the array by just providing
the array name followed by its corresponding subscript.
It is easy to edit/modify any data item within the array.

A linear linked list is defined as a collection of nodes in which each node has two
parts: (i) information part and (ii) link part.

When we represent a group of items as a linear linked list, the items are not
contiguously aligned in memory but instead they are linked to each other via
pointers. The information part of each node of the linear linked list contains the
value of the items and the link part contains the address of the next node in the
linear linked list. The last node of the linear linked list contains the NULL
pointer in its link part indicating the end of the linear linked list. [Give
structure of linked list and the process of insertion and deletion of
items]

Prepared by Kriti Nemkul 50


50
The advantages of linear linked lists are as follows:
Linear Linked lists are dynamic data structures: They can
grow or shrink during the execution of aprogram.
Efficient memory utilization: Memory is not pre-allocated. Memory is allocated
whenever required and deallocated (removed) when it is not needed.
Insertion and deletions are easier and efficient: Linear linked lists provide
flexibility in inserting a data item at a specified position and deletion of a data item
from the given position.

The disadvantages of linked lists are as follows:


Access to an arbitrary data item is little bit cumbersome and also time-consuming.
A linked list uses more storage than an array with the same number of items. This
is because each item has an additional link field.

Prepared by Kriti Nemkul 51


51
Linked list implementation
of Stack

Prepared by Kriti Nemkul 52


Linked list implementation of Stack
• Push function:
let *top be the top of the stack or pointer to the first node of the list.
void push(item)
{
NodeType *nnode;
int data;
nnode=( NodeType *)malloc(sizeof(NodeType));
if(top==0)
{
nnode->info=item;
nnode->next=NULL;
top=nnode;
}
else
{
nnode->info=item;
nnode->next=top;
top=nnode;
}
}

Prepared by Kriti Nemkul 53


• Pop function:
let *top be the top of the stack or pointer to the first
node of the list.
void pop()
{
NodeType *temp;
if(top==0)
{
printf("Stack contain no elements:\n");
return;
}
else
{
temp=top;
top=top->next;
printf("\ndeleted item is %d\t",temp->info);
free(temp);
}
}

Prepared by Kriti Nemkul 54


• Display stack elements

Prepared by Kriti Nemkul 55


Linked list implementation of queue
• Insert Function
let *rear and *front are pointers to the first node of the list initially and
insertion of node in linked list done at the rear part and deletion of node
from the linked list done from front part.

Prepared by Kriti Nemkul 56


void insert(int item)
{
NodeType *nnode;
nnode=( NodeType *)malloc(sizeof(NodeType));
if(rear==0)
{
nnode->info=item;
nnode->next=NULL ;
rear=front=nnode;
}
else
{
nnode->info=item;
nnode->next=NULL;
rear->next=nnode;
rear=nnode;
}
}

Prepared by Kriti Nemkul 57


• Deleting an element from queue
void dequeue()
{
NodeType *temp;
if(front==0)
{
printf("Queue contain no elements:\n");
return;
}
else if(front->next==NULL)
{
temp=front;
rear=front=NULL;
printf("\nDeleted item is %d\n",temp->info);
free(temp);
}
else
{
temp=front;
front=front->next;
printf("\nDeleted item is %d\n",temp->info);
free(temp);
}
}

Prepared by Kriti Nemkul 58


• Displaying the elements of queue
void display()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL\n",temp->data);
}

Prepared by Kriti Nemkul 59


Circular Linked List
• A circular linked list is a list where the link field of last node points to
the very first node of the list.
• Circular linked lists can be used to help the traverse the same list again
and again if needed. A circular list is very similar to the linear list
where in the circular list the pointer of the last node points not
NULL but the first node.
• Problem: Cannot traverse list in backward direction

Prepared by Kriti Nemkul 60


Circular Linked List…
• In a circular linked list there are two methods to know if a node is the
first node or not.
Either a external pointer, list, points the first node or
A header node is placed as the first node of the circular list.
• The header node can be separated from the others by either heaving a
sentinel value as the info part or having a dedicated flag variable to
specify if the node is a header node or not

Prepared by Kriti Nemkul 61


C representation of circular linked list
• we declare the structure for the circular linked list in the same way as
declared it for the linear linked list.
struct node
{
int info;
struct node *next;
};
typedef struct node NodeType;
NodeType *start=NULL:
NodeType *last=NULL:

Prepared by Kriti Nemkul 62


Algorithm to insert in a circular linked list
At the beginning of circular void InsertAtBeg(int Item)
{
linked list NodeType *newnode;
newnode=(NodeType*)malloc(sizeof(NodeType));
1. Create a new node as if(start==NULL)
newnode=(NodeType*)malloc(sizeof(NodeType)); {
2. if start==NULL then newnode->info=item;
set newnode->info=item newnode->next=newnode;
set newnode->next=newnode start=newnode;
set start=newnode last newnode;
set last newnode }
end if else
3. else {
set newnode->info=item newnode->info=item;
set newnode->next=start last->next=newnode;
set start=newnode last=newnode;
set last->next=newnode last->next=start;
end else }
4. End }

Prepared by Kriti Nemkul 63


Algorithm to insert in a circular linked list…
void InsertAtEnd(int Item)
At the end of circular linked list {
1. Create a new node as NodeType *newnode;
newnode=(NodeType*)malloc(sizeof(N newnode=(NodeType*)malloc(sizeof(NodeType)
odeType)); );
2. if start==NULL then if(start==NULL)
set newnode->info=item {
set newnode->next=newnode newnode->info=item;
set start=newnode newnode->next=newnode;
set last newnode start=newnode;
end if last newnode;
3. else
set newnode->info=item }
set last->next=newnode else
set last=newnode {
set last->next=start newnode->info=item;
end else last->next=newnode;
4. End last=newnode;
last->next=start;
}}
Prepared by Kriti Nemkul 64
Algorithm to delete a node from circular linked list
From the beginning void DeleteFirst()
{
1. if start==NULL then “empty list” if(start==NULL)
and exit {
2. else printf(“Empty list”);
exit(1);
set temp=start }
set start=start->next else
{
print the deleted element=temp->info temp=start;
set last->next=start; start=start->next;
printf(“ the deleted element=%d”, temp-
free(temp) >info);
end else last->next=start;
3. End free(temp)
}}
Prepared by Kriti Nemkul 65
Algorithm to delete a node from circular linked list
From the end void DeleteLast()
{
1. if start==NULL then if(start==NULL)
“empty list” and exit {
printf(“Empty list”);
2. else if start==last exit(1);
set temp=start }
print deleted element=temp->info else if(start==last) //for only one node
free(temp) {
start=last=NULL temp=start;
printf(“deleted element=%d”, temp->info);
3. else free(temp);
set temp=start start=last=NULL;
while( temp->next!=last) }
set temp=temp->next else
end while {
set hold=temp->next temp=start;
while( temp->next!=last)
set last=temp temp=temp->next;
set last->next=start hold=temp->next;
print the deleted element=hold->info last=temp;
free(hold) last->next=start;
end else printf(“the deleted element=%d”, hold->info);
free(hold);
4. End }
}

Prepared by Kriti Nemkul 66


Stack as circular list
• To implement a stack in a circular linked list, let pstack be a pointer to
the last node of a circular list. Actually there is no any end of a list but
for convention let us assume that the first node(rightmost node of a
list) is the top of the stack.
• An empty stack is represented by a null list.
• The structure for the circular linked list implementation of stack is:
struct node
{
int info;
struct node *next;
};
typedef struct node NodeType;
NodeType *pstack=NULL;

Prepared by Kriti Nemkul 67


Push Function
void PUSH(int item)
{
NodeType newnode;
newnode=(NodeType*)malloc(sizeof(NodeType));
newnode->info=item;
if(pstack==NULL)
{
pstack=newnode;
pstack->next=pstack;
}
else
{
newnode->next=pstack->next;
pstack->next=newnode;
}
}

Prepared by Kriti Nemkul 69


POP Function
void POP()
{
NodeType *temp;
if(pstack==NULL)
{
printf(“Stack underflow\n');
exit(1);
}
else if(pstack->next==pstack) //for only one node
{
printf(“poped item=%d”, pstack->info);
pstack=NULL;
}
else
{
temp=pstack->next;
pstack->next=temp->next;
printf(“poped item=%d”, temp->info);
free(temp);
}
}
Prepared by Kriti Nemkul 70
Queue as a circular list
• It is easier to represent a queue as a circular list than as a linear list. As
a linear list a queue is specified by two pointers, one to the front of the
list and the other to its rear.
• However, by using a circular list, a queue may be specified by a single
pointer q to that list. node(q) is the rear of the queue and the following
node is its front.

Prepared by Kriti Nemkul 71


Insertion Function
void insert(int item)
{
NodeType *nnode;
nnode=( NodeType *)malloc(sizeof(NodeType));
nnode->info=item;
if(pq==NULL)
pq=nnode;
else
{
nnode->next=pq->next;
pq->next=nnode;
pq=nnode;
}
}

Prepared by Kriti Nemkul 72


Delete function
void delet(int item)
{
NodeType *temp;
if(pq==NULL)
{
printf(“void deletion\n”);
exit(1);
}
else if(pq->next==pq) //for only one node
{
printf(“deleted item=%d”, pq->info);
pq=NULL;
}
else
{
temp=pq->next;
pq->next=temp->next;
printf(“deleted item=%d”, temp->info);
free(temp);
}
}
Prepared by Kriti Nemkul 73
Doubly Linked List
• A linked list in which all nodes are linked together by multiple number
of links i.e each node contains three fields (two pointer fields and one
data field) rather than two fields is called doubly linked list.
• It provides bidirectional traversal.

Prepared by Kriti Nemkul 74


Doubly Linked list as ADT
• EmptyList
• MakeListLeft(element, list), which takes an element and a doubly
linked list and returns a new doubly linked list with the element added
to the left of the original doubly linked list.
• MakeListRight(element, list), which takes an element and a doubly
linked list and returns a new doubly linked list with the element added
to the right of the original doubly linked list.

Prepared by Kriti Nemkul 75


C representation of doubly linked list:
struct node
{
int info;
struct node *prev;
struct node *next;
};
typedef struct node NodeType;
NodeType *head=NULL:

Prepared by Kriti Nemkul 76


Algorithm to insert node
• Algorithm to insert a node at the beginning of a doubly linked
list:
1.Allocate memory for the new node as,
newnode=(NodeType*)malloc(sizeof(NodeType))
2. Assign value to info field of a new node
set newnode->info=item
3. set newnode->prev=newnode->next=NULL// if list is empty
4. set newnode->next=head
5. set head->prev=newnode
6. set head=newnode
7. End

Prepared by Kriti Nemkul 77


C function to insert a node at the beginning of a
doubly linked list:
void InsertAtBeg(int Item)
{
NodeType *newnode;
newnode=(NodeType*)malloc(sizeof(NodeType));
newnode->info=item;
newnode->prev=NULL;
if(head == NULL)
{
newNode -> next = NULL;
head = newNode;
}
newnode->next=head;
head->prev=newnode;
head=newnode;
}

Prepared by Kriti Nemkul 78


Algorithm to insert a node at the end of a doubly
linked list:
1. Allocate memory for the new node as,
newnode=(NodeType*)malloc(sizeof(NodeType))
2. Assign value to info field of a new node
set newnode->info=item
3. set newnode->next=NULL
4. if head==NULL
set newnode->prev=NULL;
set head=newnode;
5. if head!=NULL
set temp=head
while(temp->next!=NULL)
temp=temp->next;
end while
set temp->next=newnode;
set newnode->prev=temp
6. End

Prepared by Kriti Nemkul 79


C function to insert a node at the end of a doubly
linked list:
void insertAtEnd(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> data = value;
newNode -> next = NULL;
if(head == NULL)
{
newNode -> previous = NULL;
head = newNode;
}
else
{
struct Node *temp = head;
while(temp -> next != NULL){
temp = temp -> next;}
temp -> next = newNode;
newNode -> previous = temp;
}
printf("\nInsertion success!!!");
}

Prepared by Kriti Nemkul 80


Algorithm to insert a node at the specific position
of a doubly 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, assign NULL to both newNode →
previous & newNode → next and set newNode to head.
• Step 4 - If it is not Empty then, define two node
pointers temp1 & temp2 and initialize temp1 with head.
• Step 5 - Keep moving the temp1 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 temp1 is reached to the last node. If it is
reached to the last node then display 'Given node is not found in the list!!!
Insertion not possible!!!' and terminate the function. Otherwise move
the temp1 to next node.
• Step 7 - Assign temp1 → next to temp2, newNode to temp1 →
next, temp1 to newNode → previous, temp2 to newNode →
next and newNode to temp2 → previous.

Prepared by Kriti Nemkul 81


Algorithm to delete a node from beginning of a
doubly linked list: void deleteBeginning()

1. if head==NULL then {
if(head == NULL)
print “empty list” and exit printf("List is Empty!!! Deletion not possible!!!");

2. else else
{
set hold=head struct Node *temp = head;

set head=head->next if(temp -> previous == temp -> next) // if list have only one node
{
set head->prev=NULL; head = NULL;

free(hold) }
free(temp);

3. End else{
head = temp -> next;
head -> previous = NULL;
free(temp);
}
printf("\nDeletion success!!!");
}}

Prepared by Kriti Nemkul 82


Algorithm to delete a node from end of a doubly
linked list: void deleteEnd()

1. if head==NULL then {

print “empty list” and exit if(head == NULL)


printf("List is Empty!!! Deletion not possible!!!");
2. else if(head->next==NULL) then else
set hold=head {
set head=NULL struct Node *temp = head;

free(hold) if(temp -> previous == temp -> next) // list has single node

3. else {
head = NULL;
set temp=head;
free(temp);
while(temp->next->next !=NULL) }
temp=temp->next else{
end while while(temp -> next != NULL)

set hold=temp->next temp = temp -> next;

set temp->next=NULL temp -> previous -> next = NULL;


free(temp);
free(hold) }
4. End printf("\nDeletion success!!!");
}
Prepared by Kriti Nemkul
} 83
Algorithm to delete a specific node from the
double liked 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 - Keep moving the temp until it reaches to the exact node to be deleted or to the last 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 fuction.
• Step 6 - If it is reached to the exact node which we want to delete, then check whether list is having only one node or not
• Step 7 - If list has only one node and that is the node which is to be deleted then set head to NULL and
delete temp (free(temp)).
• Step 8 - If list contains multiple nodes, then check whether temp is the first node in the list (temp == head).
• Step 9 - If temp is the first node, then move the head to the next node (head = head → next),
set head of previous to NULL (head → previous = NULL) and delete temp.
• Step 10 - If temp is not the first node, then check whether it is the last node in the list (temp → next == NULL).
• Step 11 - If temp is the last node then set temp of previous of next to NULL (temp → previous → next = NULL) and
delete temp (free(temp)).
• Step 12 - If temp is not the first node and not the last node, then set temp of previous of next to temp of next (temp →
previous → next = temp → next), temp of next of previous to temp of previous (temp → next → previous = temp →
previous) and delete temp (free(temp)).

Prepared by Kriti Nemkul 84


Display a double 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 - Display 'NULL <--- '.
• Step 5 - Keep displaying temp → data with an arrow (<===>)
until temp reaches to the last node
• Step 6 - Finally, display temp → data with arrow pointing
to NULL (temp → data ---> NULL).

Prepared by Kriti Nemkul 85


Circular Doubly Linked list
• A circular doubly linked list is one which has the successor and
predecessor pointer in circular manner
• It is a doubly linked list where the next link of last node points to the
first node and previous link of first node points to last node of the list.
• The main objective of considering circular doubly linked list is to
simplify the insertion and deletion operations performed on doubly
linked list.

Prepared by Kriti Nemkul 86


C representation of doubly circular linked list:
struct node
{
int info;
struct node *prev;
struct node *next;
};
typedef struct node NodeType;
NodeType *head=NULL:

Prepared by Kriti Nemkul 87


Algorithm to insert a node at the beginning of a
circular doubly linked list:
1. Allocate memory for the new node as,
newnode=(NodeType*)malloc(sizeof(NodeType))
2. Assign value to info field of a new node
set newnode->info=item
3. set temp=head->next
4. set head->next=newnode
5. set newnode->prev=head
6. set newnode->next=temp
7. set temp->prev=newnode
8. End
Prepared by Kriti Nemkul 88
Algorithm to insert a node at the end of a circular
doubly linked list:
1. Allocate memory for the new node as,
newnode=(NodeType*)malloc(sizeof(NodeType))
2. Assign value to info field of a new node
set newnode->info=item
3. set temp=head->prev
4. set temp->next=newnode
5. set newnode->prev=temp
6. set newnode->next=head
7. set head->prev=newnode
8. End
Prepared by Kriti Nemkul 89
Algorithm to delete a node from the beginning of
a circular doubly linked list:
1. if head->next==NULL then
print “empty list” and exit
2. else
set temp=head->next;
set head->next=temp->next
set temp->next=head
free(temp)
3. End

Prepared by Kriti Nemkul 90


Algorithm to delete a node from the end of a
circular doubly linked list:
1. if head->next==NULL then
print “empty list” and exit
2. else
set temp=head->prev;
set head->left=temp->left
free(temp)
3. End

Prepared by Kriti Nemkul 91


• Advantages of Doubly Linked List
• A DLL can be traversed in both forward and backward direction.
• The delete operation in DLL is more efficient if pointer to the node to
be deleted is given.
• We can quickly insert a new node before a given node.
• Disadvantages of Doubly Linked List
• Every node of DLL Require extra space for an previous pointer(This
can be overcome by implementing XOR Linked list)
• All operations require an extra pointer previous to be maintained

Prepared by Kriti Nemkul 92

You might also like