0% found this document useful (0 votes)
15 views57 pages

Unit 3 CDS

The document provides an overview of linked lists, detailing their structure, advantages over arrays, and specific operations such as insertion, deletion, and searching. It explains the concept of singly linked lists, their traversal, and the algorithms for various operations, including inserting and deleting nodes at different positions. Additionally, it includes a sample C program for implementing a menu-driven linked list management system.

Uploaded by

gammersadda3
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)
15 views57 pages

Unit 3 CDS

The document provides an overview of linked lists, detailing their structure, advantages over arrays, and specific operations such as insertion, deletion, and searching. It explains the concept of singly linked lists, their traversal, and the algorithms for various operations, including inserting and deleting nodes at different positions. Additionally, it includes a sample C program for implementing a menu-driven linked list management system.

Uploaded by

gammersadda3
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/ 57

UNIT-III

o Linked List can be defined as collection of objects called nodes that are randomly stored in the memory.
o A node contains two fields i.e. data stored at that particular address and the pointer which contains the address of
the next node in the memory.
o The last node of the list contains pointer to the null.

Uses of Linked List


o The list is not required to be contiguously present in the memory. The node can reside any where in the memory
and linked together to make a list. This achieves optimized utilization of space.
o list size is limited to the memory size and doesn't need to be declared in advance.
o Empty node can not be present in the linked list.
o We can store values of primitive types or objects in the singly linked list.

Why use linked list over array?

Till now, we were using array data structure to organize the group of elements that are to be stored individually in
the memory. However, Array has several advantages and disadvantages which must be known in order to decide
the data structure which will be used throughout the program.

Array contains following limitations:

1. The size of array must be known in advance before using it in the program.
2. Increasing size of the array is a time taking process. It is almost impossible to expand the size of the array at run
time.
3. All the elements in the array need to be contiguously stored in the memory. Inserting any element in the array
needs shifting of all its predecessors.

Linked list is the data structure which can overcome all the limitations of an array. Using linked list is useful
because,

1. It allocates the memory dynamically. All the nodes of linked list are non-contiguously stored in the memory and
linked together with the help of pointers.
2. Sizing is no longer a problem since we do not need to define its size at the time of declaration. List grows as per
the program's demand and limited to the available memory space.

Singly linked list or One way chain

Singly linked list can be defined as the collection of ordered set of elements. The number of elements may vary
according to need of the program. A node in the singly linked list consist of two parts: data part and link part. Data
part of the node stores actual information that is to be represented by the node while the link part of the node stores
the address of its immediate successor.
One way chain or singly linked list can be traversed only in one direction. In other words, we can say that each
node contains only next pointer, therefore we can not traverse the list in the reverse direction.

Consider an example where the marks obtained by the student in three subjects are stored in a linked list as shown
in the figure.

In the above figure, the arrow represents the links. The data part of every node contains the marks obtained by the
student in the different subject. The last node in the list is identified by the null pointer which is present in the
address part of the last node. We can have as many elements we require, in the data part of the list.

Complexity
Data Time Complexity Space
Structure Compleity

Average Worst Worst

Access Search Insertion Deletion Access Search Insertion Deletion

Singly θ(n) θ(n) θ(1) θ(1) O(n) O(n) O(1) O(1) O(n)
Linked List

Operations on Singly Linked List

There are various operations which can be performed on singly linked list. A list of all such operations is
given below.

Node Creation
1. struct node
2. {
3. int data;
4. struct node *next;
5. };
6. struct node *head, *ptr;
7. ptr = (struct node *)malloc(sizeof(struct node *));

Insertion:

The insertion into a singly linked list can be performed at different positions. Based on the position of the
new node being inserted, the insertion is categorized into the following categories.
S.No Operation Description

1 Insertion at It involves inserting any element at the front of the list. We just need to
beginning a few link adjustments to make the new node as the head of the list.

2 Insertion at end It involves insertion at the last of the linked list. The new node can be
of the list inserted as the only node in the list or it can be inserted as the last one.
Different logics are implemented in each scenario.

3 Insertion after It involves insertion after the specified node of the linked list. We need
specified node to skip the desired number of nodes in order to reach the node after
which the new node will be inserted. .

Deletion and Traversing:

The Deletion of a node from a singly linked list can be performed at different positions. Based on the position
of the node being deleted, the operation is categorized into the following categories.

S.No Operation Description

1 Deletion at It involves deletion of a node from the beginning of the list. This is the simplest
beginning operation among all. It just need a few adjustments in the node pointers.

2 Deletion at the It involves deleting the last node of the list. The list can either be empty or full.
end of the list Different logic is implemented for the different scenarios.

3 Deletion after It involves deleting the node after the specified node in the list. we need to skip the
specified node desired number of nodes to reach the node after which the node will be deleted. This
requires traversing through the list.

4 Traversing In traversing, we simply visit each node of the list at least once in order to perform
some specific operation on it, for example, printing data part of each node present
in the list.

5 Searching In searching, we match each element of the list with the given element. If the element
is found on any of the location then location of that element is returned otherwise
null is returned. .
Inserting Elements to a Linked List
We will see how a new node can be added to an existing linked list in the following cases.

1. The new node is inserted at the beginning.


2. The new node is inserted at the end.
3. The new node is inserted after a given node.

Insert a Node at the beginning of a Linked list:

Consider the linked list shown in the figure. Suppose we want to create a new node with data 24 and add it as the
first node of the list. The linked list will be modified as follows.

 Allocate memory for new node and initialize its DATA part to 24.
 Add the new node as the first node of the list by pointing the NEXT part of the new node to HEAD.
 Make HEAD to point to the first node of the list.
Algorithm: InsertAtBeginning

Step 1: IF AVAIL = NULL


Write OVERFLOW
Go to Step 7
[END OF IF]
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET NEW_NODE -> NEXT = HEAD
Step 6: SET HEAD = NEW_NODE
Step 7: EXIT
Note that the first step of the algorithm checks if there is enough memory available to create a new node. The
second, and third steps allocate memory for the new node.

This algorithm can be implemented in C as follows:

struct node *new_node;


new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = 24;
new_node->next = head;
head = new_node;

Insert a Node at the end of a Linked list:


Take a look at the linked list in the figure. Suppose we want to add a new node with data 24 as the last node of the
list. Then the linked list will be modified as follows.

 Allocate memory for new node and initialize its DATA part to 24.
 Traverse to last node.
 Point the NEXT part of the last node to the newly created node.
 Make the value of next part of last node to NULL.
Algorithm: InsertAtEnd

Step 1: IF AVAIL = NULL


Write OVERFLOW
Go to Step 10
[END OF IF]
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET NEW_NODE -> NEXT = NULL
Step 6: SET PTR = HEAD
Step 7: Repeat Step 8 while PTR -> NEXT != NULL
Step 8: SET PTR = PTR -> NEXT
[END OF LOOP]
Step 9: SET PTR -> NEXT = NEW_NODE
Step 10: EXIT
This can be implemented in C as follows,

struct node *new_node;


new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = 24;
new_node->next = NULL;
struct node *ptr = head;
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new_node;
Insert a Node after a given Node in a Linked list:

The last case is when we want to add a new node after a given node. Suppose we want to add a new node with
value 24 after the node having data 9. These changes will be done in the linked list.
 Allocate memory for new node and initialize its DATA part to 24.
 Traverse the list until the specified node is reached.
 Change NEXT pointers accordingly.
Algorithm: InsertAfterAnElement

Step 1: IF AVAIL = NULL


Write OVERFLOW
Go to Step 12
[END OF IF]
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET PTR = HEAD
Step 6: SET PREPTR = PTR
Step 7: Repeat Steps 8 and 9 while PREPTR -> DATA != NUM
Step 8: SET PREPTR = PTR
Step 9: SET PTR = PTR -> NEXT
[END OF LOOP]
Step 1 : PREPTR -> NEXT = NEW_NODE
Step 11: SET NEW_NODE -> NEXT = PTR
Step 12: EXIT

Deleting Elements from a Linked List


Let’s discuss how a node can be deleted from a linked listed in the following cases.

1. The first node is deleted.


2. The last node is deleted.
3. The node after a given node is deleted

Delete a Node from the beginning of a Linked list:


Suppose we want to delete a node from the beginning of the linked list. The list has to be modified as follows:
 Check if the linked list is empty or not. Exit if the list is empty.
 Make HEAD points to the second node.
 Free the first node from memory.

Algorithm: DeleteFromBeginning

Step 1: IF HEAD = NULL


Write UNDERFLOW
Go to Step 5
[END OF
IF]
Step 2: SET PTR = HEAD
Step 3: SET HEAD = HEAD ->
NEXTStep 4: FREE PTR
Step 5: EXIT
This can be implemented in C as follows,

if(head == NULL)
{
printf("Underflow");
}
else
{
ptr = head;
head = head -> next;
free(ptr);
}

Delete last Node from a Linked list:


Suppose we want to delete the last node from the linked list. The linked list has to be modified as follows:
Algorithm: DeleteAfterANode

Step 1: IF HEAD = NULL


Write UNDERFLOW
Go to Step
10[END OF
IF]
Step 2: SET PTR =
HEAD Step 3: SET
PREPTR = PTR
Step 4: Repeat Steps 5 and 6 while PREPTR -> DATA !=
NUM Step 5: SET PREPTR = PTR

Traverse the list upto the specified node.


Change value of next pointer of previous node(9) to next pointer of current node(10).
Step 6: SET PTR = PTR ->
NEXT[END OF LOOP]
Step 7: SET TEMP = PTR
Step 8: SET PREPTR -> NEXT = PTR ->
NEXTStep 9: FREE TEMP
Step 10 : EXIT

Implementation in C takes the following form:

if(head == NULL)
{
printf("Underflow");
}
else
{
struct node* ptr =
head; struct node*
preptr = ptr; while(ptr-
>data!=num){ preptr =
ptr;
ptr = ptr->next;
}
struct node* temp = ptr;
preptr -> next = ptr ->
next; free(temp);
}

Search
Finding an element is similar to a traversal operation. Instead of displaying data, we have to check whether the data matches
with the item to find.

 Initialize PTR with the address of HEAD. Now the PTR points to the first node of the linked list.
 A while loop is executed which will compare data of every node with item.
 If item has been found then control goes to last step.

Algorithm: Search

Step 1: [INITIALIZE] SET PTR = HEAD


Step 2: Repeat Steps 3 and 4 while PTR != NULL
Step 3: If ITEM = PTR ->
DATASET POS = PTR
Go To Step 5
ELSE
SET PTR = PTR ->
NEXT[END OF IF]
[END OF LOOP]
Step 4: SET POS = NULL
Step 5: EXIT
Search operation can be implemented in C as follows:

struct node* ptr = head;


struct node* pos =
NULL; while (ptr !=
NULL) {
if (ptr->data ==
item)pos = ptr
printf("Element Found");
break
; else
ptr = ptr -> next;
}

Linked List in C: Menu Driven Program


1. #include<stdio.h>
2. #include<stdlib.h>
3. struct node
4. {

5. int data;
6. struct node *next;
7. };
8. struct node *head;
9.
10. void beginsert ();
11. void lastinsert ();
12. void randominsert();
13. void begin_delete();
14. void last_delete();
15. void random_delete();
16. void display();
17. void search();
18. void main ()
19. {
20. int choice =0;
21. while(choice != 9)
22. {
23. printf("\n\n*********Main Menu*********\n");
24. printf("\nChoose one option from the following list ...\n");
25. printf("\n===============================================\n");
26. printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random location\n4.Delete from Beginni
ng\n
27. 5.Delete from last\n6.Delete node after specified location\n7.Search for an element\n8.Show\n9.Exit\n
");
28. printf("\nEnter your choice?\n");
29. scanf("\n%d",&choice);
30. switch(choice)
31. {
32. case 1:
33. beginsert();
34. break;
35. case 2:
36. lastinsert();
37. break;
38. case 3:
39. randominsert();
40. break;
41. case 4:
42. begin_delete();
43. break;
44. case 5:
45. last_delete();
46. break;
47. case 6:
48. random_delete();
49. break;
50. case 7:
51. search();
52. break;
53. case 8:
54. display();
55. break;
56. case 9:

57. exit(0);
58. break;
59. default:
60. printf("Please enter valid choice..");
61. }
62. }
63. }
64. void beginsert()
65. {
66. struct node *ptr;
67. int item;
68. ptr = (struct node *) malloc(sizeof(struct node *));
69. if(ptr == NULL)
70. {
71. printf("\nOVERFLOW");
72. }
73. else
74. {
75. printf("\nEnter value\n");
76. scanf("%d",&item);
77. ptr->data = item;
78. ptr->next = head;
79. head = ptr;
80. printf("\nNode inserted");
81. }
82.
83. }
84. void lastinsert()
85. {
86. struct node *ptr,*temp;
87. int item;
88. ptr = (struct node*)malloc(sizeof(struct node));
89. if(ptr == NULL)
90. {
91. printf("\nOVERFLOW");
92. }
93. else
94. {
95. printf("\nEnter value?\n");
96. scanf("%d",&item);
97. ptr->data = item;
98. if(head == NULL)
99. {
100. ptr -> next = NULL;
101. head = ptr;
102. printf("\nNode inserted");
103. }
104. else
105. {
106. temp = head;
107. while (temp -> next != NULL)
108. {
109. temp = temp -> next;
110. }
111. temp->next = ptr;
112. ptr->next = NULL;
113. printf("\nNode inserted");
114.
115. }
116. }
117. }
118. void randominsert()
119. {
120. int i,loc,item;
121. struct node *ptr, *temp;
122. ptr = (struct node *) malloc (sizeof(struct node));
123. if(ptr == NULL)
124. {
125. printf("\nOVERFLOW");
126. }
127. else
128. {
129. printf("\nEnter element value");
130. scanf("%d",&item);
131. ptr->data = item;
132. printf("\nEnter the location after which you want to insert ");
133. scanf("\n%d",&loc);
134. temp=head;
135. for(i=0;i<loc;i++)
136. {
137. temp = temp->next;
138. if(temp == NULL)
139. {
140. printf("\ncan't insert\n");
141. return;
142. }
143.
144. }
145. ptr ->next = temp ->next;
146. temp ->next = ptr;
147. printf("\nNode inserted");
148. }
149. }
150. void begin_delete()
151. {
152. struct node *ptr;
153. if(head == NULL)
154. {
155. printf("\nList is empty\n");
156. }
157. else
158. {
159. ptr = head;
160. head = ptr->next;
161. free(ptr);
162. printf("\nNode deleted from the begining ...\n");
163. }
164. }

165. void last_delete()


166. {
167. struct node *ptr,*ptr1;
168. if(head == NULL)
169. {
170. printf("\nlist is empty");
171. }
172. else if(head -> next == NULL)
173. {
174. head = NULL;
175. free(head);
176. printf("\nOnly node of the list deleted ...\n");
177. }
178.
179. else
180. {
181. ptr = head;
182. while(ptr->next != NULL)
183. {
184. ptr1 = ptr;
185. ptr = ptr ->next;
186. }
187. ptr1->next = NULL;
188. free(ptr);
189. printf("\nDeleted Node from the last ...\n");
190. }
191. }
192. void random_delete()
193. {
194. struct node *ptr,*ptr1;
195. int loc,i;
196. printf("\n Enter the location of the node after which you want to perform deletion \n");
197. scanf("%d",&loc);
198. ptr=head;
199. for(i=0;i<loc;i++)
200. {
201. ptr1 = ptr;
202. ptr = ptr->next;
203.
204. if(ptr == NULL)
205. {
206. printf("\nCan't delete");
207. return;
208. }
209. }
210. ptr1 ->next = ptr ->next;
211. free(ptr);
212. printf("\nDeleted node %d ",loc+1);
213. }
214. void search()
215. {
216. struct node *ptr;
217. int item,i=0,flag;
218. ptr = head;

219. if(ptr == NULL)


220. {
221. printf("\nEmpty List\n");
222. }
223. else
224. {
225. printf("\nEnter item which you want to search?\n");
226. scanf("%d",&item);
227. while (ptr!=NULL)
228. {
229. if(ptr->data == item)
230. {
231. printf("item found at location %d ",i+1);
232. flag=0;
233. }
234. else
235. {
236. flag=1;
237. }
238. i++;
239. ptr = ptr -> next;
240. }
241. if(flag==1)
242. {
243. printf("Item not found\n");
244. }
245. }
246.
247. }
248.
249. void display()
250. {
251. struct node *ptr;
252. ptr = head;
253. if(ptr == NULL)
254. {
255. printf("Nothing to print");
256. }
257. else
258. {
259. printf("\nprinting values..........\n");
260. while (ptr!=NULL)
261. {
262. printf("\n%d",ptr->data);
263. ptr = ptr -> next;
264. }
265. }
266. }
267.

Output:
*********Main Menu*********

Choose one option from the following list ...

===============================================

1. Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit

Enter your choice?


1

Enter value
1

Node inserted

*********Main Menu*********

Choose one option from the following list ...

===============================================

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit

Enter your choice?


2

Enter value?
2

Node inserted

*********Main Menu*********
Choose one option from the following list ...
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit

Enter your choice?


3

Enter element value1

Enter the location after which you want to insert 1

Node inserted

*********Main Menu*********

Choose one option from the following list ...

===============================================

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit

Enter your choice?


8

printing values . . . . .

1
2
1

*********Main Menu*********

Choose one option from the following list ...

===============================================
5. Delete from last
6. Delete node after specified location
7.Search for an element
8.Show
9.Exit

Enter your choice?


2

Enter value?
123

Node inserted

*********Main Menu*********

Choose one option from the following list ...

===============================================

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit

Enter your choice?


1

Enter value
1234

Node inserted

*********Main Menu*********

Choose one option from the following list ...

===============================================

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
Enter your choice?
4

Node deleted from the begining ...

*********Main Menu*********

Choose one option from the following list ...

===============================================

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit

Enter your choice?


5

Deleted Node from the last ...

*********Main Menu*********

Choose one option from the following list ...

===============================================

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit

Enter your choice?


6

Enter the location of the node after which you want to perform deletion
1

Deleted node 2
*********Main Menu*********

Choose one option from the following list ...===============================================

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit

Enter your choice?


8

printing values . . . . .

1
1

*********Main Menu*********

Choose one option from the following list ...

===============================================

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit

Enter your choice?


7

Enter item which you want to search?


1
item found at location 1
item found at location 2

*********Main Menu*********

Choose one option from the following list ...


===============================================

5. Delete from last


6. Delete node after specified location
7.Search for an element
8.Show
9.Exit

Enter your choice?


9

Traverse a Linked List


Accessing the nodes of a linked list in order to process it is called traversing a linked list. Normally we use the
traverse operation to display the contents or to search for an element in the linked list. The algorithm for traversing a
linked list is given below.

Algorithm: Traverse

Step 1: [INITIALIZE] SET PTR = HEAD


Step 2: Repeat Steps 3 and 4 while PTR != NULL
Step 3: Apply process to PTR -> DATA
Step 4: SET PTR = PTR->NEXT
[END OF LOOP]
Step 5: EXIT
We first initialize PTR with the address of HEAD. Now the PTR points to the first node of the linked list.
A while loop is executed, and the operation is continued until PTR reaches the last node (PTR = NULL).
Apply the process(display) to the current node.
Move to the next node by making the value of PTR to the address of next node.
The following block of code prints all elements in a linked list in C.

struct node *ptr = head;


printf("Elements in the linked list are : ");
while (ptr != NULL)
{
printf("%d ", ptr->data);
ptr = ptr->next;

}
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 andpeek.
In linked list implementation of stack, the nodes are maintained non-contiguously in the memory. Each nodecontains a
pointer to its immediate successor node in the stack. Stack is said to be overflown if the space leftin the memory heap is
not enough to create a node.

The top most node in the stack always contains null in its address field. Lets discuss the way in which, each
operation is performed in linked list implementation of stack.

Adding a node to the stack (Push operation):


Adding a node to the stack is referred to as push operation. Pushing an element to a stack in linked list implementation
is different from that of an array implementation. In order to push an element onto the stack, the following steps are
involved.

1. create a node first and allocate memory to it.


2. If the list is empty then the item is to be pushed as the start node of the list. This includes assigning valueto
the data part of the node and assign null to the address part of the node.
3. If there are some nodes in the list already, then we have to add the new element in the beginning of the list
(to not violate the property of the stack). For this purpose, assign the address of the starting element to the
address field of the new node and make the new node, the starting node of the list.

Time Complexity : o(1)


C implementation :
1. void push ()
2. {
3. int val;
4. struct node *ptr =(struct node*)malloc(sizeof(struct node));
5. if(ptr == NULL)
6. {
7. printf("not able to push the element");
8. }
9. else
10. {
11. printf("Enter the value");
12. scanf("%d",&val);
13. if(head==NULL)
14. {
15. ptr->val = val;
16. ptr -> next = NULL;
17. head=ptr;
18. }
19. else

20. {
21. ptr->val = val;
22. ptr->next = head;
23. head=ptr;

24.
25. }
26. printf("Item pushed");
27.
28. }
29. }

Deleting a node from the stack (POP operation)

Deleting a node from the top of stack is referred to as pop operation. Deleting a node from the linked list
implementation of stack is different from that in the array implementation. In order to pop an element from the
stack, we need to follow the following steps :

1. Check for the underflow condition: The underflow condition occurs when we try to pop from an already
empty stack. The stack will be empty if the head pointer of the list points to null.
2. Adjust the head pointer accordingly: In stack, the elements are popped only from one end, therefore, the
value stored in the head pointer must be deleted and the node must be freed. The next node of the head nodenow
becomes the head node.

Time Complexity : o(n)

C implementation
1. void pop()
2. {
3. int item;
4. struct node *ptr;
5. if (head ==
NULL)6. {
7.
printf("Underflow");
8. }
9. else
10. {
11. item = head->val;
12. ptr = head;
13. head = head->next;
14. free(ptr);
15. printf("Item popped");

16.
17. }
18. }
Display the nodes (Traversing)

Displaying all the nodes of a stack needs traversing all the nodes of the linked list organized in the formof 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)

C Implementation
1. void display()
2. {
3. int i;
4. struct node *ptr;
5. ptr=head;
6. if(ptr == NULL)
7. {
8. printf("Stack is
empty\n");9. }
10. else
11. {
12. printf("Printing Stack elements \n");
13. while(ptr!=NULL)
14. {
15. printf("%d\n",ptr->val);
16. ptr = ptr->next;
17. }
18. }
19. }
Menu Driven program in C implementing all the stack operations usinglinked list :
1. #include <stdio.h>
2. #include <stdlib.h>
3. void push();
4. void pop();
5. void display();

6. struct node
7. {
8. int val;
9. struct node *next;
10. };
11. struct node *head;
12.
13. void main ()
14. {
15. int choice=0;
16. printf("\n*********Stack operations using linked list*********\n");
17. printf("\n \n");
18. while(choice != 4)
19. {
20. printf("\n\nChose one from the below options...\n");
21. printf("\n1.Push\n2.Pop\n3.Show\n4.Exit");
22. printf("\n Enter your choice \n");
23. scanf("%d",&choice);
24. switch(choice)
25. {
26. case 1:
27. {
28. push();
29. break;
30. }
31. case 2:
32. {
33. pop();
34. break;
35. }
36. case 3:
37. {
38. display();
39. break;
40. }
41. case 4:
42. {
43. printf("Exiting.
");
44. break;
45. }

default:
46.
47. {
48. printf("Please Enter valid choice
");
49. }
50. };
51. }
52. }
53. void push ()
54. {
55. int val;
56. struct node *ptr = (struct node*)malloc(sizeof(struct node));
57. if(ptr == NULL)
58. {
59. printf("not able to push the element");
60. }
61. else
62. {
63. printf("Enter the value");
64. scanf("%d",&val);
65. if(head==NULL)
66. {
67. ptr->val = val;
68. ptr -> next = NULL;
69. head=ptr;
70. }
71. else
72. {
73. ptr->val = val;
74. ptr->next = head;
75. head=ptr;
76.76.
77. }
78. printf("Item
pushed");79.
80. }
81.
}82.
83. void pop()
84. {
85. int item;

86. struct node *ptr;


87. if (head == NULL)
88. {
89. printf("Underflow");
90. }
91. else
92. {
93. item = head->val;
94. ptr = head;
95. head = head->next;
96. free(ptr);
97. printf("Item
popped");98.
99. }
100. }
101. void display()
102. {
103. int i;
104. struct node *ptr;
105. ptr=head;
106. if(ptr == NULL)
107. {
108. printf("Stack is empty\n");
109. }
110. else
111. {
112. printf("Printing Stack elements \n");
113. while(ptr!=NULL)
114. {
115. printf("%d\n",ptr->val);
116. ptr = ptr->next;
117. }
118. }
119. }

Linked List implementation of Queue

The storage requirement of linked representation of a queue with n elements is o(n) while the timerequirement
for operations is o(1).

In a linked queue, each node of the queue consists of two parts i.e. data part and the link part. Eachelement of the
queue points to its immediate next element in the memory.

1. In the linked queue, there are two pointers maintained in the memory i.e. front pointer and rear pointer. The front
pointer contains the address of the starting element of the queue while the rear pointer contains the address of
the last element of the queue. rear -> next = ptr;
2. rear = ptr;
3. rear->next = NULL;

In this way, the element is inserted into the queue. The algorithm and the C implementation is givenas follows.

Algorithm
o Step 1: Allocate the space for the new node PTR
o Step 2: SET PTR -> DATA = VAL
o Step 3: IF FRONT =
NULLSET FRONT =
REAR = PTR
SET FRONT -> NEXT = REAR -> NEXT =
NULLELSE
SET REAR -> NEXT =
PTRSET REAR = PTR
SET REAR -> NEXT =
NULL[END OF IF]
o Step 4: END
C Function
1. void insert(struct node *ptr, int item;
)2. {
3.
4.
5. ptr = (struct node *) malloc (sizeof(struct node));
6. if(ptr == NULL)
7. {
8. printf("\nOVERFLOW\n");
9. return;
10. }
11. else
12. {
13. ptr -> data = item;
14. if(front == NULL)

15. {
16. front = ptr;
17. rear = ptr;
18. front -> next = NULL;
19. rear -> next = NULL;
20. }
21. else
22. {
23. rear -> next = ptr;
24. rear = ptr;
25. rear->next = NULL;
26. }
27. }
28. }
Deletion

Deletion operation removes the element that is first inserted among all the queue elements. Firstly, we need to check
either the list is empty or not. The condition front == NULL becomes true if the list is empty,in this case , we simply
write underflow on the console and make exit.

Otherwise, we will delete the element that is pointed by the pointer front. For this purpose, copy the nodepointed by
the front pointer into the pointer ptr. Now, shift the front pointer, point to its next node and free the node pointed by
the node ptr. This is done by using the following statements.

1. ptr = front;
2. front = front -> next;
3. free(ptr);
The algorithm and C function is given as follows.

Algorithm
o Step 1: IF FRONT =
NULLWrite " Underflow
"
Go to Step 5
[END OF
IF]
o Step 2: SET PTR = FRONT
o Step 3: SET FRONT = FRONT -> NEXT
o Step 4: FREE PTR
o Step 5: END

C Function
1. void delete (struct node *ptr)2.
{
3. if(front ==
NULL)4. {
5. printf("\nUNDERFLOW\n");
6. return;7.
}
8. else
9. {
10. ptr = front;
11. front = front -> next;
12. free(ptr);
13. }
14. }
Menu-Driven Program implementing all the operations on
Linked Queue
1. #include<stdio.h>
2. #include<stdlib.h>
3. struct node
4. {
5. int data;
6. struct node *next;
7. };
8. struct node *front;
9. struct node *rear;
10. void insert();
11. void delete();
12. void display();
13. void main ()
14. {
15. int choice;
16. while(choice != 4)
17. {
18. printf("\n*************************Main Menu*****************************\n");
19. printf("\n===========================================================
======\n");
20. printf("\n1.insert an element\n2.Delete an element\n3.Display the queue\n4.Exit\n");
21. printf("\nEnter your choice ?");

22. scanf("%d",& choice);


23. switch(choice)
24. {
25. case 1:
26. insert();
27. break;
28. case 2:
29. delete();
30. break;
31. case 3:
32. display();
33. break;
34. case 4:
35. exit(0);
36. break;
37. default:
38. printf("\nEnter valid choice??\n");
39. }
40. }
41. }
42. void insert()
43. {
44. struct node *ptr;
45. int
item;46.
47. ptr = (struct node *) malloc (sizeof(struct node));
48. if(ptr == NULL)
49. {
50. printf("\nOVERFLOW\n");
51. return;
52. }
53. else
54. {
55. printf("\nEnter value?\n");
56. scanf("%d",&item);
57. ptr -> data = item;
58. if(front == NULL)
59. {
60. front = ptr;
61. rear = ptr;

62. front -> next = NULL;


63. rear -> next = NULL;
64. }
65. else
66. {
67. rear -> next = ptr;
68. rear = ptr;
69. rear->next = NULL;
70. }
71. }
72. }
73. void delete ()
74. {
75. struct node *ptr;
76. if(front == NULL)
77. {
78. printf("\nUNDERFLOW\n");
79. return;
80. }
81. else
82. {
83. ptr = front;
84. front = front -> next;
85. free(ptr);
86. }
87. }
88. void display()
89. {
90. struct node *ptr;
91. ptr = front;
92. if(front == NULL)
93. {
94. printf("\nEmpty queue\n");
95. }
96. else
97. { printf("\nprinting values ... \n");
98. while(ptr != NULL)
99. {
100. printf("\n%d\n",ptr -> data);
101. ptr = ptr -> next;

102. }
103. }
104. }

Output:

***********Main Menu**********

==============================

1. insertan element
2.Delete an element
3.Display the queue
4.Exit

Enter your choice ?1

Enter value?
123

***********Main Menu**********

==============================

1.insert an element
2.Delete an element
3.Display the queue
4.Exit

Enter your choice ?1

Enter value?90

***********Main Menu**********
==============================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit

Enter your choice ?3

printing values .....

90

***********Main Menu**********

==============================

1.insert an element
2.Delete an element
3.Display the queue
4.Exit

Enter your choice ?4

Polynomials using linked list


linked list is a data structure that stores each element as an object in a node of the list. every note contains two parts
data han and links to the next node.
Polynomial is a mathematical expression that consists of variables and coefficients. for example x^2 - 4x + 7
In the Polynomial linked list, the coefficients and exponents of the polynomial are defined as the data node of the
list.
For adding two polynomials that are stored as a linked list. We need to add the coefficients of variables with the same
power. In a linked list node contains 3 members, coefficient value link to the next node.
a linked list that is used to store Polynomial looks like −
Polynomial : 4x7 + 12x2 + 45

This is how a linked list represented polynomial looks like.


Adding two polynomials that are represented by a linked list. We check values at the exponentvalue of the
node. For the same values of exponent, we will add the coefficients.

Example,
Input :
p1= 13x8 + 7x5 + 32x2 +
54 p2= 3x12 + 17x5 + 3x3
+ 98

Output : 3x12 + 13x8 + 24x5 + 3x3 + 32x2 + 152


Explanation − For all power, we will check for the coefficients of the exponents that have thesame value
of exponents and add them. The return the final polynomial.
Algorithm
Input − polynomial p1 and p2 represented as a linked list.
Step 1: loop around all values of linked list and follow step 2& 3.
Step 2: if the value of a node’s exponent. is greater copy this node to result node and head towards the
nextnode.
Step 3: if the values of both node’s exponent is same add the coefficients and then copy the added value
withnode to the result.
Step 4: Print the resultant node
Given two polynomial numbers represented by a linked list. Write a function that addthese lists
means add the coefficients who have same variable powers.
Example:
Input:

1st number = 5x2 + 4x1 + 2x02nd


number = -5x1 - 5x0
Output:
5x2-1x1-3x0
Input:
1st number = 5x3 + 4x2 + 2x02nd
number = 5x^1 - 5x^0
Output:
5x3 + 4x2 + 5x1 - 3x0
Doubly linked list

Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next
node in the sequence. Therefore, in a doubly linked list, a node consists of three parts: node data,pointer to the next node
in sequence (next pointer) , pointer to the previous node (previous pointer). A sample node in a doubly linked list is
shown in the figure.

A doubly linked list containing three nodes having numbers from 1 to 3 in their data part, is shown in the following
image.

In C, structure of a node in doubly linked list can be given as :

1. struct node
2. {
3. struct node *prev;
4. int data;
5. struct node *next;6.
}

The prev part of the first node and the next part of the last node will always contain null indicating end ineach
direction.

Operations on doubly linked list

Node Creation

1. struct node
2. {
3. struct node *prev;
4. int data;
5. struct node *next;
6. };
7. struct node *head;

All the remaining operations regarding doubly linked list are described in the following table.
SN Operation Description

1 Insertion at beginning Adding the node into the linked list at beginning.

2 Insertion at end Adding the node into the linked list to the end.

3 Insertion after specified Adding the node into the linked list after the specified node.
node

4 Deletion at beginning Removing the node from beginning of the list

5 Deletion at the end Removing the node from end of the list.

6 Deletion of the node Removing the node which is present just after the node
having given data containing the given data.

7 Searching Comparing each node data with the item to be searched and
return the location of the item in the list if the item found else
return null.

8 Traversing Visiting each node of the list at least once in order to perform
some specific operation like searching, sorting, display, etc.

Insertion in doubly linked list at beginning

As in doubly linked list, each node of the list contain double pointers therefore we have to maintain morenumber of
pointers in doubly linked list as compare to singly linked list.

There are two scenarios of inserting any element into doubly linked list. Either the list is empty or it contains at least
one element. Perform the following steps to insert a node in doubly linked list at beginning.

o Allocate the space for the new node in the memory. This will be done by using the following statement.

1. ptr = (struct node *)malloc(sizeof(struct node));


o Check whether the list is empty or not. The list is empty if the condition head == NULL holds. In that case, the node
will be inserted as the only node of the list and therefore the prev and the next pointer of the node will point to NULL
and the head pointer will point to this node.

1. ptr->next = NULL;
2. ptr->prev=NULL;
3. ptr->data=item;
4. head=ptr;
o In the second scenario, the condition head == NULL become false and the node will be inserted in beginning. The
next pointer of the node will point to the existing head pointer of the node. The prev pointer of the existing head will
point to the new node being inserted.
o This will be done by using the following statements.

1. ptr->next = head;
2. head→prev=ptr;

Since, the node being inserted is the first node of the list and therefore it must contain NULL in its prevpointer.
Hence assign null to its previous part and make the head point to this node.

1. ptr→prev =NULL
2. head = ptr
Algorithm :
Step 1: IF ptr = NULL
Write
OVERFLOWGo
to Step 9 [END
OF IF]
Step 2: SET NEW_NODE = ptr
Step 3: SET ptr = ptr -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET NEW_NODE -> PREV = NULL
Step 6: SET NEW_NODE -> NEXT = START
Step 7: SET head -> PREV = NEW_NODE
Step 8: SET head = NEW_NODE
Step 9: EXIT

Insertion in doubly linked list at the end

In order to insert a node in doubly linked list at the end, we must make sure whether the list is empty or itcontains any
element. Use the following steps in order to insert the node in doubly linked list at the end.

o Allocate the memory for the new node. Make the pointer ptr point to the new node being inserted.

1. ptr = (struct node *) malloc(sizeof(struct node));


o Check whether the list is empty or not. The list is empty if the condition head == NULL holds. In that case, the node
will be inserted as the only node of the list and therefore the prev and the next pointer of the node will point to NULL
and the head pointer will point to this node.

1. ptr->next = NULL;
2. ptr->prev=NULL;
3. ptr->data=item;
4. head=ptr;
o In the second scenario, the condition head == NULL become false. The new node will be inserted as the last node of
the list. For this purpose, we have to traverse the whole list in order to reach the last node of the list. Initialize the
pointer temp to head and traverse the list by using this pointer.

1. Temp = head;
2. while (temp !=
NULL)3. {
4. temp = temp → next;
5. }

the pointer temp point to the last node at the end of this while loop. Now, we just need to make a few pointer
adjustments to insert the new node ptr to the list. First, make the next pointer of temp point to thenew node being
inserted i.e. ptr.

1. temp→next =ptr;

make the previous pointer of the node ptr point to the existing last node of the list i.e. temp.

1. ptr → prev = temp;

make the next pointer of the node ptr point to the null as it will be the new last node of the list.

1. ptr → next = NULL


Algorithm
Step 1: IF PTR = NULL
Write
OVERFLOWGo
to Step 11 [END
OF IF]
Step 2: SET NEW_NODE = PTR
Step 3: SET PTR = PTR -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET NEW_NODE -> NEXT = NULL
Step 6: SET TEMP = START
Step 7: Repeat Step 8 while TEMP -> NEXT != NULL
Step 8: SET TEMP = TEMP -> NEXT
 [END OF LOOP]
Step 9: SET TEMP -> NEXT = NEW_NODE
Step 10C: SET NEW_NODE -> PREV = TEMP
Step 11: EXIT
Insertion in doubly linked list after Specified node

In order to insert a node after the specified node in the list, we need to skip the required number of nodesin order to
reach the mentioned node and then make the pointer adjustments as required.

Use the following steps for this purpose.

o Allocate the memory for the new node. Use the following statements for this.

1. ptr = (struct node *)malloc(sizeof(struct node));


o Traverse the list by using the pointer temp to skip the required number of nodes in order to reach the specified
node.

1. temp=head;
2. for(i=0;i<loc;i++)

3. {
4. temp = temp->next;
5. if(temp == NULL) // the temp will be //null if the list doesn't last long //up to mentioned location
6. {
7.
return;8.
}
9. }
o The temp would point to the specified node at the end of the for loop. The new node needs to be inserted after this
node therefore we need to make a fer pointer adjustments here. Make the next pointer of ptr point to the next node
of temp.

1. ptr → next = temp → next;

make the prev of the new node ptr point to temp.

1. ptr → prev = temp;

make the next pointer of temp point to the new node ptr.

1. temp → next = ptr;

make the previous pointer of the next node of temp point to the new node.
1. temp → next → prev = ptr;
Algorithm
o Step 1: IF PTR = NULL

Write
OVERFLOWGo to
Step 15 [END OF
IF]

o Step 2: SET NEW_NODE = PTR


o Step 3: SET PTR = PTR -> NEXT
o Step 4: SET NEW_NODE -> DATA = VAL
o Step 5: SET TEMP = START
o Step 6: SET I = 0
o Step 7: REPEAT 8 to 10 until I<="" li="">
o Step 8: SET TEMP = TEMP -> NEXT
o STEP 9: IF TEMP = NULL
o STEP 10: WRITE "LESS THAN DESIRED NO. OF ELEMENTS"

GOTO STEP
15[END OF IF]
[END OF LOOP]

o Step 11: SET NEW_NODE -> NEXT = TEMP -> NEXT


o Step 12: SET NEW_NODE -> PREV = TEMP
o Step 13 : SET TEMP -> NEXT = NEW_NODE
o Step 14: SET TEMP -> NEXT -> PREV = NEW_NODE
o Step 15: EXIT

Deletion at beginning

Deletion in doubly linked list at the beginning is the simplest operation. We just need to copy the headpointer to
pointer ptr and shift the head pointer to its next.

1. Ptr = head;
2. head = head → next;

now make the prev of this new head node point to NULL. This will be done by using the followingstatements.

1. head → prev = NULL

Now free the pointer ptr by using the free function.

1. free(ptr)
Algorithm
o STEP 1: IF HEAD = NULL

WRITE
UNDERFLOWGOTO
STEP 6

o STEP 2: SET PTR = HEAD


o STEP 3: SET HEAD = HEAD → NEXT
o STEP 4: SET HEAD → PREV = NULL
o STEP 5: FREE PTR
o STEP 6: EXIT

Deletion in doubly linked list at the end

Deletion of the last node in a doubly linked list needs traversing the list in order to reach the last node ofthe 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.

o If the list is already empty then the condition head == NULL will become true and therefore the operation
can not be carried on.
o 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.
o Otherwise, just traverse the list to reach the last node of the list. This will be done by using the following
statements.

1. ptr = head;
2. if(ptr->next != NULL)
3. {
4. ptr = ptr -> next;
5. }

o The ptr would point to the last node of the ist at the end of the for loop. Just make the next pointer of the
previous node of ptr to NULL.

1. ptr → prev → next = NULL

free the pointer as this the node which is to be deleted.

1. free(ptr)
o Step 1: IF HEAD = NULL

Write UNDERFLOW
Go to Step 7
[END OF IF]

o Step 2: SET TEMP = HEAD


o Step 3: REPEAT STEP 4 WHILE TEMP->NEXT != NULL
o Step 4: SET TEMP = TEMP->NEXT

[END OF LOOP]

o Step 5: SET TEMP ->PREV-> NEXT = NULL


o Step 6: FREE TEMP
o Step 7: EXIT

Deletion in doubly linked list after the specified node

In order to delete the node after the specified data, we need to perform the following steps.

o Copy the head pointer into a temporary pointer temp.

1. temp = head
o Traverse the list until we find the desired data value.

1. while(temp -> data != val)


2. temp = temp -> next;
o Check if this is the last node of the list. If it is so then we can't perform deletion.

1. if(temp -> next ==


NULL)2. {
3. return;
4. }
o Check if the node which is to be deleted, is the last node of the list, if it so then we have to make thenext
pointer of this node point to null so that it can be the new last node of the list.

1. if(temp -> next -> next == NULL)


2. {
3. temp ->next =
NULL;4. }
o Otherwise, make the pointer ptr point to the node which is to be deleted. Make the next of temppoint to
the next of ptr. Make the previous of next node of ptr point to temp. free the ptr.

1. ptr = temp -> next;


2. temp -> next = ptr -> next;
3. ptr -> next -> prev = temp;
4. free(ptr);
Algorithm
o Step 1: IF HEAD = NULL

Write UNDERFLOW
Go to Step 9
[END OF IF]

o Step 2: SET TEMP = HEAD


o Step 3: Repeat Step 4 while TEMP -> DATA != ITEM
o Step 4: SET TEMP = TEMP -> NEXT

[END OF LOOP]

o Step 5: SET PTR = TEMP -> NEXT


o Step 6: SET TEMP -> NEXT = PTR -> NEXT

o Step 7: SET PTR -> NEXT -> PREV = TEMP


o Step 8: FREE PTR
o Step 9: EXIT

Searching for a specific node in Doubly Linked List

We just need traverse the list in order to search for a specific element in the list. Perform followingoperations in
order to search a specific operation.
o Copy head pointer into a temporary pointer variable ptr.

1. ptr = head
o declare a local variable I and assign it to 0.

1. i=0
o Traverse the list until the pointer ptr becomes null. Keep shifting pointer to its next and increasing i by +1.
o Compare each element of the list with the item which is to be searched.
o If the item matched with any node value then the location of that value I will be returned from the function else
NULL is returned.

Algorithm
o Step 1: IF HEAD == NULL

WRITE
"UNDERFLOW"GOTO
STEP 8
[END OF IF]

o Step 2: Set PTR = HEAD


o Step 3: Set i = 0
o Step 4: Repeat step 5 to 7 while PTR != NULL
o Step 5: IF PTR → data = item

return i
[END OF IF]

o Step 6: i = i + 1
o Step 7: PTR = PTR → next
o Step 8: Exit

Traversing in doubly linked list

Traversing is the most common operation in case of each data structure. For this purpose, copy the headpointer in any
of the temporary pointer ptr.

1. Ptr = head

then, traverse through the list by using while loop. Keep shifting value of pointer variable ptr untilwe find
the last node. The last node contains null in its next part.

1. while(ptr !=
NULL)2. {
3. printf("%d\n",ptr->data);
4. ptr=ptr->next;
5. }
Although, traversing means visiting each node of the list once to perform some specific operation. Here, weare
printing the data associated with each node of the list.

Algorithm
o Step 1: IF HEAD == NULL

WRITE
"UNDERFLOW"GOTO
STEP 6
[END OF IF]

o Step 2: Set PTR = HEAD


o Step 3: Repeat step 4 and 5 while PTR != NULL
o Step 4: Write PTR → data
o Step 5: PTR = PTR → next

o Step 6: Exit

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 singlyliked 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.

Operations on Circular Singly linked list:


Insertion
SN Operation Description

1 Insertion at beginning Adding a node into circular singly linked list at the beginning.

2 Insertion at the end Adding a node into circular singly linked list at the end.

Deletion & Traversing


SN Operation Description
1 Deletion at Removing the node from circular singly linked list at the beginning.
beginning

2 Deletion at the Removing the node from circular singly linked list at the end.
end

3 Searching Compare each element of the node with the given item and return the locationat
which the item is present in the list otherwise return null.

4 Traversing Visiting each element of the list at least once in order to perform some specific
operation.

Insertion into circular singly linked list at beginning

There are two scenario in which a node can be inserted in circular singly linked list at beginning. Either the
node will be inserted in an empty list or the node is to be inserted in an already filled list.

Firstly, allocate the memory space for the new node by using the malloc method of C language.

1. struct node *ptr = (struct node *)malloc(sizeof(struct node));

In the first scenario, the condition head == NULL will be true. Since, the list in which, we are inserting the
node is a circular singly linked list, therefore the only node of the list (which is just inserted into the list) will
point to itself only. We also need to make the head pointer point to this node. This will be done by using the
following statements.

1. if(head ==
NULL)2. {
3. head = ptr;
4. ptr -> next = head;5.
}

In the second scenario, the condition head == NULL will become false which means that the list contains at
least one node. In this case, we need to traverse the list in order to reach the last nodeof the list. This will be
done by using the following statement.

1. temp = head;
2. while(temp->next != head)
3. temp = temp->next;

At the end of the loop, the pointer temp would point to the last node of the list. Since, in a circularsingly linked
list, the last node of the list contains a pointer to the first node of the list. Therefore, we need to make the
next pointer of the last node point to the head node of the list and the new node which is being inserted into
the list will be the new head node of the list therefore the next pointer of temp will point to the new node ptr.

This will be done by using the following statements.

1. temp -> next = ptr;


the next pointer of temp will point to the existing head node of the list.
1. ptr->next = head;

Now, make the new node ptr, the new head node of the circular singly linked list.

1. head = ptr;

in this way, the node ptr has been inserted into the circular singly linked list at beginning.

Algorithm
o Step 1: IF PTR = NULL

Write
OVERFLOWGo to
Step 11 [END OF
IF]

o Step 2: SET NEW_NODE = PTR


o Step 3: SET PTR = PTR -> NEXT
o Step 4: SET NEW_NODE -> DATA = VAL
o Step 5: SET TEMP = HEAD
o Step 6: Repeat Step 8 while TEMP -> NEXT != HEAD
o Step 7: SET TEMP = TEMP -> NEXT

[END OF LOOP]

o Step 8: SET NEW_NODE -> NEXT = HEAD


o Step 9: SET TEMP → NEXT = NEW_NODE
o Step 10: SET HEAD = NEW_NODE
o Step 11: EXIT
Insertion into circular singly linked list at the end

There are two scenario in which a node can be inserted in circular singly linked list at beginning. Either thenode will be
inserted in an empty list or the node is to be inserted in an already filled list.

 Firstly, allocate the memory space for the new node by using the malloc method of C language.

1. struct node *ptr = (struct node *)malloc(sizeof(struct node));

In the first scenario, the condition head == NULL will be true. Since, the list in which, we are inserting
the node is a circular singly linked list, therefore the only node of the list (which is just inserted into the
list) will point to itself only. We also need to make the head pointer point to this node. This will be done by
using the following statements.

1. if(head ==
NULL) 2. {
3. head = ptr;
4. ptr -> next = head;
5. }

In the second scenario, the condition head == NULL will become false which means that the list contains
at least one node. In this case, we need to traverse the list in order to reach the last node of the list. This
will be done by using the following statement.

1. temp = head;
2. while(temp->next != head)
3. temp = temp->next;

At the end of the loop, the pointer temp would point to the last node of the list. Since, the new node which
is being inserted into the list will be the new last node of the list. Therefore the existing last node
i.e. temp must point to the new node ptr. This is done by using the following statement.

1. temp -> next = ptr;

The new last node of the list i.e. ptr will point to the head node of the list.

1. ptr -> next = head;

In this way, a new node will be inserted in a circular singly linked list at the beginning.

Algorithm
o Step 1: IF PTR = NULL

Write
OVERFLOWGo
to Step 1 [END OF
IF]
o Step 2: SET NEW_NODE = PTR
o Step 3: SET PTR = PTR -> NEXT
o Step 4: SET NEW_NODE -> DATA = VAL
o Step 5: SET NEW_NODE -> NEXT = HEAD
o Step 6: SET TEMP = HEAD
o Step 7: Repeat Step 8 while TEMP -> NEXT != HEAD
o Step 8: SET TEMP = TEMP -> NEXT

[END OF LOOP]

o Step 9: SET TEMP -> NEXT = NEW_NODE


o Step 10: EXIT

Deletion in circular singly linked list at beginning

In order to delete a node in circular singly linked list, we need to make a few pointer adjustments.There are three

scenarios of deleting a node from circular singly linked list at beginning.

Scenario 1: (The list is Empty)

If the list is empty then the condition head == NULL will become true, in this case, we just need toprint
underflow on the screen and make exit.

1. if(head ==
NULL)2. {
3. printf("\nUNDERFLOW");
4. return;
5. }
Scenario 2: (The list contains single node)

If the list contains single node then, the condition head → next == head will become true. In this case, weneed to
delete the entire list and make the head pointer free. This will be done by using the following statements.

if(head->next == head)

1. {
2. head = NULL;
3. free(head);
4. }
Scenario 3: (The list contains more than one node)

If the list contains more than one node then, in that case, we need to traverse the list by using thepointer ptr
to reach the last node of the list. This will be done by using the following statements.

1. ptr = head;
2. while(ptr -> next != head)
3. ptr = ptr -> next;

At the end of the loop, the pointer ptr point to the last node of the list. Since, the last node of the list pointsto the head
node of the list. Therefore this will be changed as now, the last node of the list will point to thenext of the head node.

1. ptr->next = head->next;

Now, free the head pointer by using the free() method in C language.

1. free(head);

Make the node pointed by the next of the last node, the new head of the list.

1. head = ptr->next;

In this way, the node will be deleted from the circular singly linked list from the beginning.

Algorithm
o Step 1: IF HEAD = NULL

Write UNDERFLOW
Go to Step 8
[END OF IF]
o Step 2: SET PTR = HEAD
o Step 3: Repeat Step 4 while PTR → NEXT != HEAD
o Step 4: SET PTR = PTR → next

[END OF LOOP]

o Step 5: SET PTR → NEXT = HEAD → NEXT


o Step 6: FREE HEAD
o Step 7: SET HEAD = PTR → NEXT
o Step 8: EXIT

Deletion in Circular singly linked list at the end

There are three scenarios of deleting a node in circular singly linked list at the end.

Scenario 1 (the list is empty)

If the list is empty then the condition head == NULL will become true, in this case, we just need toprint
underflow on the screen and make exit.

1. if(head ==
NULL)2. {
3. printf("\nUNDERFLOW");
4. return;5.
}
Scenario 2(the list contains single element)

If the list contains single node then, the condition head → next == head will become true. In thiscase, we
need to delete the entire list and make the head pointer free. This will be done by using the following
statements.

1. if(head->next == head)
2. {
3. head = NULL;
4. free(head);
5. }
Scenario 3(the list contains more than one element)

If the list contains more than one element, then in order to delete the last element, we need to reach the last
node. We also need to keep track of the second last node of the list. For this purpose,the two pointers ptr and
preptr are defined. The following sequence of code is used for this purpose.

1. while(ptr ->next != head)


2. {
3. preptr=ptr;
4. ptr = ptr->next;
5. }

now, we need to make just one more pointer adjustment. We need to make the next pointer of preptr point to
the next of ptr (i.e. head) and then make pointer ptr free.

1. preptr->next = ptr -> next;


2. free(ptr);
Algorithm
o Step 1: IF HEAD = NULL

Write UNDERFLOW
Go to Step 8
[END OF IF]

o Step 2: SET PTR = HEAD


o Step 3: Repeat Steps 4 and 5 while PTR -> NEXT != HEAD
o Step 4: SET PREPTR = PTR
o Step 5: SET PTR = PTR -> NEXT

[END OF LOOP]
o Step 6: SET PREPTR -> NEXT = HEAD
o Step 7: FREE PTR
o Step 8: EXIT

Searching in circular singly linked list

Searching in circular singly linked list needs traversing across the list. The item which is to be searched in the list is
matched with each node data of the list once and if the match found then the location of that item is returned otherwise
-1 is returned.

The algorithm and its implementation in C is given as follows.

Algorithm
o Step 1: SET PTR = HEAD
o Step 2: Set I = 0
o STEP 3: IF PTR = NULL

WRITE "EMPTY
LIST"GOTO STEP 8
END OF IF

o STEP 4: IF HEAD → DATA =

ITEMWRITE i+1 RETURN

[END OF IF]
o STEP 5: REPEAT STEP 5 TO 7 UNTIL PTR->next != head
o STEP 6: if ptr → data = item
write i+1
RETUR
N
End of IF

o STEP 7: I = I + 1
o STEP 8: PTR = PTR → NEXT

[END OF LOOP]

o STEP 9: EXIT

Traversing in Circular Singly linked list

Traversing in circular singly linked list can be done through a loop. Initialize the temporary pointer variable temp to
head pointer and run the while loop until the next pointer of temp becomes head. The algorithm and the c function
implementing the algorithm is described as follows.

Algorithm
o STEP 1: SET PTR = HEAD
o STEP 2: IF PTR = NULL

WRITE "EMPTY
LIST"GOTO STEP 8
END OF IF

o STEP 4: REPEAT STEP 5 AND 6 UNTIL PTR → NEXT != HEAD


o STEP 5: PRINT PTR → DATA
o STEP 6: PTR = PTR → NEXT

[END OF LOOP]

o STEP 7: PRINT PTR→ DATA


o STEP 8: EXIT

Circular Doubly Linked List


o Circular doubly linked list is a more complexed type of data structure in which a node contain pointers toits previous
node as well as the next node. Circular doubly linked list doesn't contain NULL in any of the node. The last node of
the list contains the address of the first node of the list. The first node of the list also contain address of the last node
in its previous pointer.
o A circular doubly linked list is shown in the following figure.
Operations on circular doubly linked list :

There are various operations which can be performed on circular doubly linked list. The node
structure of a circular doubly linked list is similar to doubly linked list. However, the operations
on circular doubly linkedlist is described in the following table.

Operation Description

1 Insertion at beginning Adding a node in circular doubly linked list at the beginning.

2 Insertion at end Adding a node in circular doubly linked list at the end.

3 Deletion at beginning Removing a node in circular doubly linked list from beginning.

4 Deletion at end Removing a node in circular doubly linked list at the end.

Traversing and searching in circular doubly linked list is similar to that in the circular
singly linked list.

You might also like