Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
542 views

Circular Linked List Data Structure

The document describes a circular linked list data structure. A circular linked list is a variation of a linked list where the last node points to the first node, forming a circular connection between nodes. This can be implemented for both singly and doubly linked lists. Basic operations like insertion, deletion, and traversal are discussed. Code examples in C++ demonstrate how to implement these operations on a circular linked list.

Uploaded by

Adrian Iosif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
542 views

Circular Linked List Data Structure

The document describes a circular linked list data structure. A circular linked list is a variation of a linked list where the last node points to the first node, forming a circular connection between nodes. This can be implemented for both singly and doubly linked lists. Basic operations like insertion, deletion, and traversal are discussed. Code examples in C++ demonstrate how to implement these operations on a circular linked list.

Uploaded by

Adrian Iosif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Data Structure - Circular Linked

List
Circular Linked List is a variation of Linked list in which the first element points to the last element and the
last element points to the first element. Both Singly Linked List and Doubly Linked List can be made into a
circular linked list.

Singly Linked List as Circular


In singly linked list, the next pointer of the last node points to the first node.

Doubly Linked List as Circular


In doubly linked list, the next pointer of the last node points to the first node and the previous pointer of
the first node points to the last node making the circular in both directions.

As per the above illustration, following are the important points to be considered.
 The last link's next points to the first link of the list in both cases of singly as well as doubly linked list.
 The first link's previous points to the last of the list in case of doubly linked list.

Basic Operations
Following are the important operations supported by a circular list.
 insert − Inserts an element at the start of the list.
 delete − Deletes an element from the start of the list.
 display − Displays the list.

Insertion Operation
Following code demonstrates the insertion operation in a circular linked list based on single linked list.
Example
insertFirst(data):
Begin
create a new node
node -> data := data
if the list is empty, then
head := node
next of node = head
else
temp := head
while next of temp is not head, do
temp := next of temp
done
next of node := head
next of temp := node
head := node
end if
End

Deletion Operation
Following code demonstrates the deletion operation in a circular linked list based on single linked list.
deleteFirst():
Begin
if head is null, then
it is Underflow and return
else if next of head = head, then
head := null
deallocate head
else
ptr := head
while next of ptr is not head, do
ptr := next of ptr
next of ptr = next of head
deallocate head
head := next of ptr
end if
End

Display List Operation


Following code demonstrates the display list operation in a circular linked list.
display():
Begin
if head is null, then
Nothing to print and return
else
ptr := head
while next of ptr is not head, do
display data of ptr
ptr := next of ptr
display data of ptr
end if
End
Circular Linked List Data Structure In C++
With Illustration
Last Updated:November 10, 2019

A Complete Overview Of Circular Linked List.


A circular linked list is a variation of the linked list. It is a linked list whose nodes are connected in such a way
that it forms a circle.

In the circular linked list, the next pointer of the last node is not set to null but it contains the address of the first
node thus forming a circle.

Circular Linked List In C++


The arrangement shown below is for a singly linked list.

A circular linked list can be a singly linked list or a doubly linked list. In a doubly circular linked list, the previous
pointer of the first node is connected to the last node while the next pointer of the last node is connected to the
first node.

Its representation is shown below.

Declaration
We can declare a node in a circular linked list as any other node as shown below:
struct Node
{
int data;
struct Node *next;
};
In order to implement the circular linked list, we maintain an external pointer “last” that points to the last node in
the circular linked list. Hence last->next will point to the first node in the linked list.

By doing this we ensure that when we insert a new node at the beginning or at the end of the list, we need not
traverse the entire list. This is because the last points to the last node while last->next points to the first node.

This wouldn’t have been possible if we had pointed the external pointer to the first node.

Basic Operations
The circular linked list supports insertion, deletion, and traversal of the list. We will discuss each of the
operations in detail now.
Insertion
We can insert a node in a circular linked list either as a first node (empty list), in the beginning, in the end, or in
between the other nodes. Let us see each of these insertion operations using a pictorial representation below.

#1) Insert in an empty list

When there are no nodes in circular list and the list is empty, the last pointer is null, then we insert a new node
N by pointing the last pointer to the node N as shown above. The next pointer of N will point to the node N itself
as there is only one node. Thus N becomes the first as well as last node in the list.

#2) Insert at the beginning of the list

As shown in the above representation, when we add a node at the beginning of the list, the next pointer of the
last node points to the new node N thereby making it a first node.

N->next = last->next
Last->next = N
#3) Insert at the end of the list
To insert a new node at the end of the list, we follow these steps:
N-> next = last ->next;
last ->next = N
last = N
#4) Insert in between the list

Suppose we need to insert a new node N between N3 and N4, we first need to traverse the list and locate the
node after which the new node is to be inserted, in this case, its N3.

After the node is located, we perform the following steps.


N -> next = N3 -> next;
N3 -> next = N
This inserts a new node N after N3.

Deletion
The deletion operation of the circular linked list involves locating the node that is to be deleted and then freeing
its memory.

For this we maintain two additional pointers curr and prev and then traverse the list to locate the node. The
given node to be deleted can be the first node, the last node or the node in between. Depending on the location
we set the curr and prev pointers and then delete the curr node.

A pictorial representation of the deletion operation is shown below.


Traversal
Traversal is a technique of visiting each and every node. In linear linked lists like singly linked list and doubly
linked lists, traversal is easy as we visit each node and stop when NULL is encountered.

However, this is not possible in a circular linked list. In a circular linked list, we start from the next of the last
node which is the first node and traverse each node. We stop when we once again reach the first node.

Now we present an implementation of the circular linked list operations using C++ and Java. We have
implemented insertion, deletion and traversal operations here. For a clear understanding, we have depicted the
circular linked list as

Thus to the last node 50, we again attach node 10 which is the first node, thereby indicating it as a circular
linked list.

1 #include<iostream>

2 using namespace std;

4 struct Node

5{

6 int data;

7 struct Node *next;

8 };

9 //insert a new node in an empty list

10 struct Node *insertInEmpty(struct Node *last, int new_data)

11 {

12 // if last is not null then list is not empty, so return

13 if (last != NULL)
14 return last;

15

16 // allocate memory for node

17 struct Node *temp = new Node;

18

19 // Assign the data.

20 temp -> data = new_data;

21 last = temp;

22

23 // Create the link.

24 last->next = last;

25

26 return last;

27 }

28 //insert new node at the beginning of the list

29 struct Node *insertAtBegin(struct Node *last, int new_data)

30 {

31 //if list is empty then add the node by calling insertInEmpty

32 if (last == NULL)

33 return insertInEmpty(last, new_data);

34

35 //else create a new node

36 struct Node *temp = new Node;

37

38 //set new data to node

39 temp -> data = new_data;

40 temp -> next = last -> next;

41 last -> next = temp;

42
43 return last;

44 }

45 //insert new node at the end of the list

46 struct Node *insertAtEnd(struct Node *last, int new_data)

47 {

48 //if list is empty then add the node by calling insertInEmpty

49 if (last == NULL)

50 return insertInEmpty(last, new_data);

51

52 //else create a new node

53 struct Node *temp = new Node;

54

55 //assign data to new node

56 temp -> data = new_data;

57 temp -> next = last -> next;

58 last -> next = temp;

59 last = temp;

60

61 return last;

62 }

63

64 //insert a new node in between the nodes

65 struct Node *insertAfter(struct Node *last, int new_data, int after_item)

66 {

67 //return null if list is empty

68 if (last == NULL)

69 return NULL;

70

71 struct Node *temp, *p;


72 p = last -> next;

73 do

74 {

75 if (p ->data == after_item)

76 {

77 temp = new Node;

78 temp -> data = new_data;

79 temp -> next = p -> next;

80 p -> next = temp;

81

82 if (p == last)

83 last = temp;

84 return last;

85 }

86 p = p -> next;

87 } while(p != last -> next);

88

89 cout << "The node with data "<<after_item << " is not present in the list." << endl;

90 return last;

91

92 }

93 //traverse the circular linked list

94 void traverseList(struct Node *last) {

95 struct Node *p;

96

97 // If list is empty, return.

98 if (last == NULL) {

99 cout << "Circular linked List is empty." << endl;

100 return;
101 }

102 p = last -> next; // Point to the first Node in the list.

103

104 // Traverse the list starting from first node until first node is visited again

105

106 do {

107 cout << p -> data << "==>";

108 p = p -> next;

109 } while(p != last->next);

110 if(p == last->next)

111 cout<<p->data;

112 cout<<"\n\n";

113 }

114

115 //delete the node from the list

116 void deleteNode(Node** head, int key)

117 {

118 // If linked list is empty retun

119 if (*head == NULL)

120 return;

121

122 // If the list contains only a single node,delete that node; list is empty

123 if((*head)->data==key && (*head)->next==*head) {

124 free(*head);

125 *head=NULL;

126 }

127 Node *last=*head,*d;

128

129 // If key is the head

130 if((*head)->data==key) {
131 while(last->next!=*head) // Find the last node of the list

132 last=last->next;

133

134 // point last node to next of head or second node of the list

135 last->next=(*head)->next;

136 free(*head);

137 *head=last->next;

138 }

139

140 // end of list is reached or node to be deleted not there in the list

141 while(last->next!=*head&&last->next->data!=key) {

142 last=last->next;

143 }

144 // node to be deleted is found, so free the memory and display the list

145 if(last->next->data==key) {

146 d=last->next;

147 last->next=d->next;

148 cout<<"The node with data "<<key<<" deleted from the list"<<endl;

149 free(d);

150 cout<<endl;

151 cout<<"Circular linked list after deleting "<<key<<" is as follows:"<<endl;

152 traverseList(last);

153 }

154 else

155 cout<<"The node with data "<< key << " not found in the list"<<endl;

156 }

157

158 // main Program

159 int main()

160 {
161 struct Node *last = NULL;

162

163 last = insertInEmpty(last, 30);

164 last = insertAtBegin(last, 20);

165 last = insertAtBegin(last, 10);

166 last = insertAtEnd(last, 40);

167 last = insertAtEnd(last, 60);

168 last = insertAfter(last, 50,40 );

169 cout<<"The circular linked list created is as follows:"<<endl;

170 traverseList(last);

171 deleteNode(&last,10);

172 return 0;

173 }

Output:
The circular linked list created is as follows:

10==>20==>30==>40==>50==>60==>10

The node with data 10 is deleted from the list

Circular linked list after deleting 10 is as follows:

20==>30==>40==>50==>60==>20

Next, we present a Java implementation for the Circular linked list operations.
1 //Java class to demonstrate circular linked list operations

2 class Main

3{

4 static class Node {

5 int data;

6 Node next;

7 };

8 //insert a new node in the empty list

9 static Node insertInEmpty(Node last, int new_data)

10 {
11 // if list is not empty, return

12 if (last != null)

13 return last;

14

15 Node temp = new Node(); // create a new node

16

17 temp.data = new_data; // assign data to new node

18 last = temp;

19

20 last.next = last; // Create the link

21

22 return last;

23 }

24 //insert a new node at the beginning of the list

25 static Node insertAtBegin(Node last, int new_data)

26 {

27 //if list is null, then return and call funciton to insert node in empty list

28 if (last == null)

29 return insertInEmpty(last, new_data);

30

31 //create a new node

32 Node temp = new Node();

33 //set data for the node

34 temp.data = new_data;

35 temp.next = last.next;

36 last.next = temp;

37

38 return last;

39 }
40 //insert a new node at the end of the list

41 static Node insertAtEnd(Node last, int new_data)

42 {

43 //if list is null, then return and call funciton to insert node in empty list

44 if (last == null)

45 return insertInEmpty(last, new_data);

46 //create a new node

47 Node temp = new Node();

48

49 temp.data = new_data;

50 temp.next = last.next;

51 last.next = temp;

52 last = temp;

53

54 return last;

55 }

56 //insert node in between the nodes in the list

57 static Node addAfter(Node last, int new_data, int after_item)

58 {

59 //if list is null, return

60 if (last == null)

61 return null;

62

63 Node temp, p;

64 p = last.next;

65 do

66 {

67 if (p.data == after_item)

68 {

69 temp = new Node();


70 temp.data = new_data;

71 temp.next = p.next;

72 p.next = temp;

73

74 if (p == last)

75 last = temp;

76 return last;

77 }

78 p = p.next;

79 { while(p != last.next);

80

81 System.out.println("The node with data " + after_item + " not present in the list.");

82 return last;

83

84 }

85 //traverse the circular linked list

86 static void traverse(Node last)

87 {

88 Node p;

89

90 // If list is empty, return.

91 if (last == null) {

92 System.out.println("Cicular linked List is empty.");

93 return;

94 }

95

96 p = last.next; // Point to first Node of the list.

97

98 // Traversing the list.

99 do{
100 System.out.print(p.data + "==>");

101 p = p.next;

102 }

103 while(p != last.next);

104 if(p == last.next)

105 System.out.print(p.data);

106 System.out.print("\n\n");

107 }

108 //delete a node from the list

109 static Node deleteNode(Node head, int key) {

110 //if list is null, return

111 if (head == null)

112 return null;

113

114 // Find the required node that is to be deleted

115 Node curr = head, prev = new Node();

116 while (curr.data != key) {

117 if (curr.next == head) {

118 System.out.printf("\nGiven node " + key + " is not found" + “in the list!");

119 break;

120 }

121 prev = curr;

122 curr = curr.next;

123 }

124 // Check if node is only node

125 if (curr.next == head) {

126 head = null;

127 return head;

128 }

129 // If more than one node, check if it is first node


130 if (curr == head) {

131 prev = head;

132 while (prev.next != head)

133 prev = prev.next;

134 head = curr.next;

135 prev.next = head;

136 }

137

138 // check if node is last node

139 else if (curr.next == head) {

140 prev.next = head;

141 }

142 else {

143 prev.next = curr.next;

144 }

145

146 System.out.println("After deleting " + key + " the circular list is:");

147 traverse(head);

148 return head;

149 }

150 // Main code

151 public static void main(String[] args){

152 Node last = null;

153

154 last = insertInEmpty(last, 30);

155 last = insertAtBegin(last, 20);

156 last = insertAtBegin(last, 10);

157 last = insertAtEnd(last, 40);

158 last = insertAtEnd(last, 60);

159 last = addAfter(last, 50, 40);


160

161 System.out.println("Circular linked list created is:");

162 traverse(last);

163 last = deleteNode(last,40);

164 }

165 }

Output:
Circular linked list created is:

10==>20==>30==>40==>50==>60==>10

After deleting 40 the circular list is:

10==>20==>30==>50==>60==>10

Advantages/Disadvantages
Let us discuss some advantages and disadvantages of the circular linked list.

Advantages:
 We can go to any node and traverse from any node. We just need to stop when we visit the same node
again.
 As the last node points to the first node, going to the first node from the last node just takes a single
step.
Disadvantages:
 Reversing a circular linked list is cumbersome.
 As the nodes are connected to form a circle, there is no proper marking for beginning or end for the list.
Hence, it is difficult to find the end of the list or loop control. If not taken care, an implementation might
end up in an infinite loop.
 We cannot go back to the previous node in a single step. We have to traverse the entire list from first.
Applications Of Circular Linked List
 Real-time application of circular linked list can be a multi-programming operating system wherein it
schedules multiple programs. Each program is given a dedicated timestamp to execute after which the
resources are passed to another program. This goes on continuously in a cycle. This representation can
be efficiently achieved using a circular linked list.
 Games that are played with multiple players can also be represented using a circular linked list in which
each player is a node that is given a chance to play.
 We can use a circular linked list to represent a circular queue. By doing this, we can remove the two
pointers front and rear that is used for the queue. Instead, we can use only one pointer.
Conclusion
A circular linked list is a collection of nodes in which the nodes are connected to each other to form a circle.
This means instead of setting the next pointer of the last node to null, it is linked to the first node.

A circular linked list is helpful in representing structures or activities which need to be repeated again and again
after a specific time interval like programs in a multiprogramming environment. It is also beneficial for designing
a circular queue.

Circular linked lists support various operations like insertion, deletion, and traversals. Thus we have seen the
operations in detail in this tutorial.
C++ Program To Implement Circular Singly Linked List
This C++ Program demonstrates circular single linked list.
Here is source code of the C++ Program to demonstrate circular single linked list. The C++ program is
successfully compiled and run on a Linux system. The program output is also shown below.
1. /*
2. * C++ Program to Implement Circular Linked List
3. */
4. #include<iostream>
5. #include<cstdio>
6. #include<cstdlib>
7. using namespace std;
8. /*
9. * Node Declaration
10. */
11. struct node
12. {
13. int info;
14. struct node *next;
15. }*last;
16.
17. /*
18. * Class Declaration
19. */
20. class circular_llist
21. {
22. public:
23. void create_node(int value);
24. void add_begin(int value);
25. void add_after(int value, int position);
26. void delete_element(int value);
27. void search_element(int value);
28. void display_list();
29. void update();
30. void sort();
31. circular_llist()
32. {
33. last = NULL;
34. }
35. };
36.
37. /*
38. * Main :contains menu
39. */
40. int main()
41. {
42. int choice, element, position;
43. circular_llist cl;
44. while (1)
45. {
46. cout<<endl<<"---------------------------"<<endl;
47. cout<<endl<<"Circular singly linked list"<<endl;
48. cout<<endl<<"---------------------------"<<endl;
49. cout<<"1.Create Node"<<endl;
50. cout<<"2.Add at beginning"<<endl;
51. cout<<"3.Add after"<<endl;
52. cout<<"4.Delete"<<endl;
53. cout<<"5.Search"<<endl;
54. cout<<"6.Display"<<endl;
55. cout<<"7.Update"<<endl;
56. cout<<"8.Sort"<<endl;
57. cout<<"9.Quit"<<endl;
58. cout<<"Enter your choice : ";
59. cin>>choice;
60. switch(choice)
61. {
62. case 1:
63. cout<<"Enter the element: ";
64. cin>>element;
65. cl.create_node(element);
66. cout<<endl;
67. break;
68. case 2:
69. cout<<"Enter the element: ";
70. cin>>element;
71. cl.add_begin(element);
72. cout<<endl;
73. break;
74. case 3:
75. cout<<"Enter the element: ";
76. cin>>element;
77. cout<<"Insert element after position: ";
78. cin>>position;
79. cl.add_after(element, position);
80. cout<<endl;
81. break;
82. case 4:
83. if (last == NULL)
84. {
85. cout<<"List is empty, nothing to delete"<<endl;
86. break;
87. }
88. cout<<"Enter the element for deletion: ";
89. cin>>element;
90. cl.delete_element(element);
91. cout<<endl;
92. break;
93. case 5:
94. if (last == NULL)
95. {
96. cout<<"List Empty!! Can't search"<<endl;
97. break;
98. }
99. cout<<"Enter the element to be searched: ";
100. cin>>element;
101. cl.search_element(element);
102. cout<<endl;
103. break;
104. case 6:
105. cl.display_list();
106. break;
107. case 7:
108. cl.update();
109. break;
110. case 8:
111. cl.sort();
112. break;
113. case 9:
114. exit(1);
115. break;
116. default:
117. cout<<"Wrong choice"<<endl;
118. }
119. }
120. return 0;
121. }
122.
123. /*
124. * Create Circular Link List
125. */
126. void circular_llist::create_node(int value)
127. {
128. struct node *temp;
129. temp = new(struct node);
130. temp->info = value;
131. if (last == NULL)
132. {
133. last = temp;
134. temp->next = last;
135. }
136. else
137. {
138. temp->next = last->next;
139. last->next = temp;
140. last = temp;
141. }
142. }
143.
144. /*
145. * Insertion of element at beginning
146. */
147. void circular_llist::add_begin(int value)
148. {
149. if (last == NULL)
150. {
151. cout<<"First Create the list."<<endl;
152. return;
153. }
154. struct node *temp;
155. temp = new(struct node);
156. temp->info = value;
157. temp->next = last->next;
158. last->next = temp;
159. }
160.
161. /*
162. * Insertion of element at a particular place
163. */
164. void circular_llist::add_after(int value, int pos)
165. {
166. if (last == NULL)
167. {
168. cout<<"First Create the list."<<endl;
169. return;
170. }
171. struct node *temp, *s;
172. s = last->next;
173. for (int i = 0;i < pos-1;i++)
174. {
175. s = s->next;
176. if (s == last->next)
177. {
178. cout<<"There are less than ";
179. cout<<pos<<" in the list"<<endl;
180. return;
181. }
182. }
183. temp = new(struct node);
184. temp->next = s->next;
185. temp->info = value;
186. s->next = temp;
187. /*Element inserted at the end*/
188. if (s == last)
189. {
190. last=temp;
191. }
192. }
193.
194. /*
195. * Deletion of element from the list
196. */
197. void circular_llist::delete_element(int value)
198. {
199. struct node *temp, *s;
200. s = last->next;
201. /* If List has only one element*/
202. if (last->next == last && last->info == value)
203. {
204. temp = last;
205. last = NULL;
206. free(temp);
207. return;
208. }
209. if (s->info == value) /*First Element Deletion*/
210. {
211. temp = s;
212. last->next = s->next;
213. free(temp);
214. return;
215. }
216. while (s->next != last)
217. {
218. /*Deletion of Element in between*/
219. if (s->next->info == value)
220. {
221. temp = s->next;
222. s->next = temp->next;
223. free(temp);
224. cout<<"Element "<<value;
225. cout<<" deleted from the list"<<endl;
226. return;
227. }
228. s = s->next;
229. }
230. /*Deletion of last element*/
231. if (s->next->info == value)
232. {
233. temp = s->next;
234. s->next = last->next;
235. free(temp);
236. last = s;
237. return;
238. }
239. cout<<"Element "<<value<<" not found in the list"<<endl;
240. }
241.
242. /*
243. * Search element in the list
244. */
245. void circular_llist::search_element(int value)
246. {
247. struct node *s;
248. int counter = 0;
249. s = last->next;
250. while (s != last)
251. {
252. counter++;
253. if (s->info == value)
254. {
255. cout<<"Element "<<value;
256. cout<<" found at position "<<counter<<endl;
257. return;
258. }
259. s = s->next;
260. }
261. if (s->info == value)
262. {
263. counter++;
264. cout<<"Element "<<value;
265. cout<<" found at position "<<counter<<endl;
266. return;
267. }
268. cout<<"Element "<<value<<" not found in the list"<<endl;
269. }
270.
271. /*
272. * Display Circular Link List
273. */
274. void circular_llist::display_list()
275. {
276. struct node *s;
277. if (last == NULL)
278. {
279. cout<<"List is empty, nothing to display"<<endl;
280. return;
281. }
282. s = last->next;
283. cout<<"Circular Link List: "<<endl;
284. while (s != last)
285. {
286. cout<<s->info<<"->";
287. s = s->next;
288. }
289. cout<<s->info<<endl;
290. }
291.
292. /*
293. * Update Circular Link List
294. */
295. void circular_llist::update()
296. {
297. int value, pos, i;
298. if (last == NULL)
299. {
300. cout<<"List is empty, nothing to update"<<endl;
301. return;
302. }
303. cout<<"Enter the node position to be updated: ";
304. cin>>pos;
305. cout<<"Enter the new value: ";
306. cin>>value;
307. struct node *s;
308. s = last->next;
309. for (i = 0;i < pos - 1;i++)
310. {
311. if (s == last)
312. {
313. cout<<"There are less than "<<pos<<" elements.";
314. cout<<endl;
315. return;
316. }
317. s = s->next;
318. }
319. s->info = value;
320. cout<<"Node Updated"<<endl;
321. }
322.
323. /*
324. * Sort Circular Link List
325. */
326. void circular_llist::sort()
327. {
328. struct node *s, *ptr;
329. int temp;
330. if (last == NULL)
331. {
332. cout<<"List is empty, nothing to sort"<<endl;
333. return;
334. }
335. s = last->next;
336. while (s != last)
337. {
338. ptr = s->next;
339. while (ptr != last->next)
340. {
341. if (ptr != last->next)
342. {
343. if (s->info > ptr->info)
344. {
345. temp = s->info;
346. s->info = ptr->info;
347. ptr->info = temp;
348. }
349. }
350. else
351. {
352. break;
353. }
354. ptr = ptr->next;
355. }
356. s = s->next;
357. }
358. }
$ g++ circular_llist.cpp
$ a.out

---------------------------------

Operations on Circular singly linked list

---------------------------------
1.Create Node
2.Add at beginning
3.Add after
4.Delete
5.Search
6.Display
7.Update
8.Sort
9.Quit
Enter your choice : 4
List is empty, nothing to delete

Circular Linked List


Circular Linked List is little more complicated linked data structure. In the circular linked list we can insert elements
anywhere in the list whereas in the array we cannot insert element anywhere in the list because it is in the contiguous
memory. In the circular linked list the previous element stores the address of the next element and the last element
stores the address of the starting element. The elements points to each other in a circular way which forms a circular
chain. The circular linked list has a dynamic size which means the memory can be allocated when it is required.
Application of Circular Linked List

 The real life application where the circular linked list is used is our Personal Computers, where multiple applications

are running. All the running applications are kept in a circular linked list and the OS gives a fixed time slot to all for

running. The Operating System keeps on iterating over the linked list until all the applications are completed.

 Another example can be Multiplayer games. All the Players are kept in a Circular Linked List and the pointer keeps on

moving forward as a player's chance ends.

 Circular Linked List can also be used to create Circular Queue. In a Queue we have to keep two pointers, FRONT and

REAR in memory all the time, where as in Circular Linked List, only one pointer is required.

Implementing Circular Linked List


Implementing a circular linked list is very easy and almost similar to linear linked list implementation, with the only
difference being that, in circular linked list the last Node will have it's next point to the Head of the List. In Linear
linked list the last Node simply holds NULL in it's next pointer.
So this will be oue Node class, as we have already studied in the lesson, it will be used to form the List.

class Node {
public:
int data;
//pointer to the next node
node* next;

node() {
data = 0;
next = NULL;
}

node(int x) {
data = x;
next = NULL;
}
}
Circular Linked List
Circular Linked List class will be almost same as the Linked List class that we studied in the previous lesson, with a
few difference in the implementation of class methods.

class CircularLinkedList {
public:
node *head;
//declaring the functions

//function to add Node at front


int addAtFront(node *n);
//function to check whether Linked list is empty
int isEmpty();
//function to add Node at the End of list
int addAtEnd(node *n);
//function to search a value
node* search(int k);
//function to delete any Node
node* deleteNode(int x);

CircularLinkedList() {
head = NULL;
}
}

Insertion at the Beginning


Steps to insert a Node at beginning :

1. The first Node is the Head for any Linked List.

2. When a new Linked List is instantiated, it just has the Head, which is Null.

3. Else, the Head holds the pointer to the fisrt Node of the List.

4. When we want to add any Node at the front, we must make the head point to it.

5. And the Next pointer of the newly added Node, must point to the previous Head, whether it be NULL(in case of new

List) or the pointer to the first Node of the List.

6. The previous Head Node is now the second Node of Linked List, because the new Node is added at the front.
int CircularLinkedList :: addAtFront(node *n) {
int i = 0;
/* If the list is empty */
if(head == NULL) {
n->next = head;
//making the new Node as Head
head = n;
i++;
}
else {
n->next = head;
//get the Last Node and make its next point to new Node
Node* last = getLastNode();
last->next = n;
//also make the head point to the new first Node
head = n;
i++;
}
//returning the position where Node is added
return i;
}

Insertion at the End


Steps to insert a Node at the end :

1. If the Linked List is empty then we simply, add the new Node as the Head of the Linked List.

2. If the Linked List is not empty then we find the last node, and make it' next to the new Node, and make the next of the

Newly added Node point to the Head of the List.

int CircularLinkedList :: addAtEnd(node *n) {


//If list is empty
if(head == NULL) {
//making the new Node as Head
head = n;
//making the next pointer of the new Node as Null
n->next = NULL;
}
else {
//getting the last node
node *last = getLastNode();
last->next = n;
//making the next pointer of new node point to head
n->next = head;
}
}

Searching for an Element in the List


In searhing we do not have to do much, we just need to traverse like we did while getting the last node, in this case
we will also compare the data of the Node. If we get the Node with the same data, we will return it, otherwise we
will make our pointer point the next Node, and so on.

node* CircularLinkedList :: search(int x) {


node *ptr = head;
while(ptr != NULL && ptr->data != x) {
//until we reach the end or we find a Node with data x, we keep moving
ptr = ptr->next;
}
return ptr;
}

Deleting a Node from the List


Deleting a node can be done in many ways, like we first search the Node with data which we want to delete and then
we delete it. In our approach, we will define a method which will take the data to be deleted as argument, will use the
search method to locate it and will then remove the Node from the List.
To remove any Node from the list, we need to do the following :

 If the Node to be deleted is the first node, then simply set the Next pointer of the Head to point to the next element

from the Node to be deleted. And update the next pointer of the Last Node as well.

 If the Node is in the middle somewhere, then find the Node before it, and make the Node before it point to the Node

next to it.

 If the Node is at the end, then remove it and make the new last node point to the head.

node* CircularLinkedList :: deleteNode(int x) {


//searching the Node with data x
node *n = search(x);
node *ptr = head;
if(ptr == NULL) {
cout << "List is empty";
return NULL;
}
else if(ptr == n) {
ptr->next = n->next;
return n;
}
else {
while(ptr->next != n) {
ptr = ptr->next;
}
ptr->next = n->next;
return n;
}
}

Circular Linked List


What is Circular Linked List?
In single linked list, every node points to its next node in the sequence and the last node points NULL. But in circular

linked list, every node points to its next node in the sequence but the last node points to the first node in the list.

A circular linked list is a sequence of elements in which every element has a link to its next element in the

sequence and the last element has a link to the first element.

That means circular linked list is similar to the single linked list except that the last node points to the first node in the list

Example
Operations
In a circular linked list, we perform the following operations...

1. Insertion

2. Deletion

3. Display

Before we implement actual operations, first we need to setup empty list. First perform the following steps before

implementing actual operations.

 Step 1 - Include all the header files which are used in the program.

 Step 2 - Declare all the user defined functions.

 Step 3 - Define a Node structure with two members data and next

 Step 4 - Define a Node pointer 'head' and set it to NULL.


 Step 5 - Implement the main method by displaying operations menu and make suitable function calls in the main

method to perform user selected operation.

Insertion
In a circular linked list, the insertion operation can be performed in three ways. They are as follows...

1. Inserting At Beginning of the list

2. Inserting At End of the list

3. Inserting At Specific location in the list

Inserting At Beginning of the list


We can use the following steps to insert a new node at beginning of the circular linked list...

 Step 1 - Create a newNode with given value.

 Step 2 - Check whether list is Empty (head == NULL)

 Step 3 - If it is Empty then, set head = newNode and newNode→next = head .

 Step 4 - If it is Not Empty then, define a Node pointer 'temp' and initialize with 'head'.

 Step 5 - Keep moving the 'temp' to its next node until it reaches to the last node (until 'temp → next == head').

 Step 6 - Set 'newNode → next =head', 'head = newNode' and 'temp → next = head'.

Inserting At End of the list


We can use the following steps to insert a new node at end of the circular linked list...

 Step 1 - Create a newNode with given value.

 Step 2 - Check whether list is Empty (head == NULL).

 Step 3 - If it is Empty then, set head = newNode and newNode → next = head.

 Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.

 Step 5 - Keep moving the temp to its next node until it reaches to the last node in the list (until temp →

next == head).

 Step 6 - Set temp → next = newNode and newNode → next = head.

Inserting At Specific location in the list (After a Node)


We can use the following steps to insert a new node after a node in the circular linked list...
 Step 1 - Create a newNode with given value.

 Step 2 - Check whether list is Empty (head == NULL)

 Step 3 - If it is Empty then, set head = newNode and newNode → next = head.

 Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.

 Step 5 - Keep moving the temp to its next node until it reaches to the node after which we want to insert the

newNode (until temp1 → data is equal to location, here location is the node value after which we want to insert

the newNode).

 Step 6 - Every time check whether temp is reached to the last node or not. If it is reached to last node then

display 'Given node is not found in the list!!! Insertion not possible!!!' and terminate the function. Otherwise

move the temp to next node.

 Step 7 - If temp is reached to the exact node after which we want to insert the newNode then check whether it is

last node (temp → next == head).

 Step 8 - If temp is last node then set temp → next = newNode and newNode → next = head.

 Step 8 - If temp is not last node then set newNode → next = temp → next and temp → next = newNode.

Deletion
In a circular linked list, the deletion operation can be performed in three ways those are as follows...

1. Deleting from Beginning of the list

2. Deleting from End of the list

3. Deleting a Specific Node

Deleting from Beginning of the list


We can use the following steps to delete a node from beginning of the circular linked list...

 Step 1 - Check whether list is Empty (head == NULL)

 Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the function.

 Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and initialize both 'temp1' and

'temp2' with head.

 Step 4 - Check whether list is having only one node (temp1 → next == head)

 Step 5 - If it is TRUE then set head = NULL and delete temp1 (Setting Empty list conditions)

 Step 6 - If it is FALSE move the temp1 until it reaches to the last node. (until temp1 → next == head )
 Step 7 - Then set head = temp2 → next, temp1 → next = head and delete temp2.

Deleting from End of the list


We can use the following steps to delete a node from end of the circular linked list...

 Step 1 - Check whether list is Empty (head == NULL)

 Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the function.

 Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and initialize 'temp1' with head.

 Step 4 - Check whether list has only one Node (temp1 → next == head)

 Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And terminate from the function.

(Setting Empty list condition)

 Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to its next node. Repeat the same

until temp1 reaches to the last node in the list. (until temp1 → next == head)

 Step 7 - Set temp2 → next = head and delete temp1.

Deleting a Specific Node from the list


We can use the following steps to delete a specific node from the circular linked list...

 Step 1 - Check whether list is Empty (head == NULL)

 Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the function.

 Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and initialize 'temp1' with head.

 Step 4 - Keep moving the temp1 until it reaches to the exact node to be deleted or to the last node. And every

time set 'temp2 = temp1' before moving the 'temp1' to its next node.

 Step 5 - If it is reached to the last node then display 'Given node not found in the list! Deletion not

possible!!!'. And terminate the function.

 Step 6 - If it is reached to the exact node which we want to delete, then check whether list is having only one node

(temp1 → next == head)

 Step 7 - If list has only one node and that is the node to be deleted then set head = NULL and

delete temp1 (free(temp1)).

 Step 8 - If list contains multiple nodes then check whether temp1 is the first node in the list (temp1 == head).

 Step 9 - If temp1 is the first node then set temp2 = head and keep moving temp2 to its next node

until temp2 reaches to the last node. Then set head = head → next, temp2 → next = head and delete temp1.
 Step 10 - If temp1 is not first node then check whether it is last node in the list (temp1 → next == head).

 Step 1 1- If temp1 is last node then set temp2 → next = head and delete temp1 (free(temp1)).

 Step 12 - If temp1 is not first node and not last node then set temp2 → next = temp1 → next and

delete temp1 (free(temp1)).

Displaying a circular Linked List


We can use the following steps to display the elements of a circular linked list...

 Step 1 - Check whether list is Empty (head == NULL)

 Step 2 - If it is Empty, then display 'List is Empty!!!' and terminate the function.

 Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with head.

 Step 4 - Keep displaying temp → data with an arrow (--->) until temp reaches to the last node

 Step 5 - Finally display temp → data with arrow pointing to head → data.

Implementation of Circular Linked List using C Programming


#include<stdio.h>
#include<conio.h>

void insertAtBeginning(int);
void insertAtEnd(int);
void insertAtAfter(int,int);
void deleteBeginning();
void deleteEnd();
void deleteSpecific(int);
void display();

struct Node
{
int data;
struct Node *next;
}*head = NULL;

void main()
{
int choice1, choice2, value, location;
clrscr();
while(1)
{
printf("\n*********** MENU *************\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\nEnter your choice: ");
scanf("%d",&choice1);
switch()
{
case 1: printf("Enter the value to be inserted: ");
scanf("%d",&value);
while(1)
{
printf("\nSelect from the following Inserting options\n");
printf("1. At Beginning\n2. At End\n3. After a Node\n4. Cancel\nEnter your cho
ice: ");
scanf("%d",&choice2);
switch(choice2)
{
case 1: insertAtBeginning(value);
break;
case 2: insertAtEnd(value);
break;
case 3: printf("Enter the location after which you want to insert: ");
scanf("%d",&location);
insertAfter(value,location);
break;
case 4: goto EndSwitch;
default: printf("\nPlease select correct Inserting option!!!\n");
}
}
case 2: while(1)
{
printf("\nSelect from the following Deleting options\n");
printf("1. At Beginning\n2. At End\n3. Specific Node\n4. Cancel\nEnter your ch
oice: ");
scanf("%d",&choice2);
switch(choice2)
{
case 1: deleteBeginning();
break;
case 2: deleteEnd();
break;
case 3: printf("Enter the Node value to be deleted: ");
scanf("%d",&location);
deleteSpecic(location);
break;
case 4: goto EndSwitch;
default: printf("\nPlease select correct Deleting option!!!\n");
}
}
EndSwitch: break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nPlease select correct option!!!");
}
}
}

void insertAtBeginning(int value)


{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> data = value;
if(head == NULL)
{
head = newNode;
newNode -> next = head;
}
else
{
struct Node *temp = head;
while(temp -> next != head)
temp = temp -> next;
newNode -> next = head;
head = newNode;
temp -> next = head;
}
printf("\nInsertion success!!!");
}
void insertAtEnd(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> data = value;
if(head == NULL)
{
head = newNode;
newNode -> next = head;
}
else
{
struct Node *temp = head;
while(temp -> next != head)
temp = temp -> next;
temp -> next = newNode;
newNode -> next = head;
}
printf("\nInsertion success!!!");
}
void insertAfter(int value, int location)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> data = value;
if(head == NULL)
{
head = newNode;
newNode -> next = head;
}
else
{
struct Node *temp = head;
while(temp -> data != location)
{
if(temp -> next == head)
{
printf("Given node is not found in the list!!!");
goto EndFunction;
}
else
{
temp = temp -> next;
}
}
newNode -> next = temp -> next;
temp -> next = newNode;
printf("\nInsertion success!!!");
}
EndFunction:
}
void deleteBeginning()
{
if(head == NULL)
printf("List is Empty!!! Deletion not possible!!!");
else
{
struct Node *temp = head;
if(temp -> next == head)
{
head = NULL;
free(temp);
}
else{
head = head -> next;
free(temp);
}
printf("\nDeletion success!!!");
}
}
void deleteEnd()
{
if(head == NULL)
printf("List is Empty!!! Deletion not possible!!!");
else
{
struct Node *temp1 = head, temp2;
if(temp1 -> next == head)
{
head = NULL;
free(temp1);
}
else{
while(temp1 -> next != head){
temp2 = temp1;
temp1 = temp1 -> next;
}
temp2 -> next = head;
free(temp1);
}
printf("\nDeletion success!!!");
}
}
void deleteSpecific(int delValue)
{
if(head == NULL)
printf("List is Empty!!! Deletion not possible!!!");
else
{
struct Node *temp1 = head, temp2;
while(temp1 -> data != delValue)
{
if(temp1 -> next == head)
{
printf("\nGiven node is not found in the list!!!");
goto FuctionEnd;
}
else
{
temp2 = temp1;
temp1 = temp1 -> next;
}
}
if(temp1 -> next == head){
head = NULL;
free(temp1);
}
else{
if(temp1 == head)
{
temp2 = head;
while(temp2 -> next != head)
temp2 = temp2 -> next;
head = head -> next;
temp2 -> next = head;
free(temp1);
}
else
{
if(temp1 -> next == head)
{
temp2 -> next = head;
}
else
{
temp2 -> next = temp1 -> next;
}
free(temp1);
}
}
printf("\nDeletion success!!!");
}
FuctionEnd:
}
void display()
{
if(head == NULL)
printf("\nList is Empty!!!");
else
{
struct Node *temp = head;
printf("\nList elements are: \n");
while(temp -> next != head)
{
printf("%d ---> ",temp -> data);
}
printf("%d ---> %d", temp -> data, head -> data);
}
}

Output

Circular Linked List | Set 2 (Traversal)


We have discussed Circular Linked List Introduction and Applications, in the previous post on Circular
Linked List. In this post, traversal operation is discussed.
Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.
In a conventional linked list, we traverse the list from the head node and stop the traversal when we reach
NULL. In a circular linked list, we stop traversal when we reach the first node again. Following is C code for
linked list traversal.

/* Function to traverse a given Circular linked list and print nodes */

void printList(struct Node *first)

struct Node *temp = first;

// If linked list is not empty

if (first != NULL)

// Keep printing nodes till we reach the first node again

do

printf("%d ", temp->data);

temp = temp->next;

while (temp != first);

Complete program to demonstrate traversal. Following are complete programs to demonstrate traversal
of circular linked list.

// C++ program to implement

// the above approach

#include <bits/stdc++.h>

using namespace std;

/* structure for a node */

class Node

public:

int data;

Node *next;

};
/* Function to insert a node at the beginning

of a Circular linked list */

void push(Node **head_ref, int data)

Node *ptr1 = new Node();

Node *temp = *head_ref;

ptr1->data = data;

ptr1->next = *head_ref;

/* If linked list is not NULL then

set the next of last node */

if (*head_ref != NULL)

while (temp->next != *head_ref)

temp = temp->next;

temp->next = ptr1;

else

ptr1->next = ptr1; /*For the first node */

*head_ref = ptr1;

/* Function to print nodes in

a given Circular linked list */

void printList(Node *head)

Node *temp = head;

if (head != NULL)

do

cout << temp->data << " ";

temp = temp->next;

}
while (temp != head);

/* Driver program to test above functions */

int main()

/* Initialize lists as empty */

Node *head = NULL;

/* Created linked list will be 11->2->56->12 */

push(&head, 12);

push(&head, 56);

push(&head, 2);

push(&head, 11);

cout << "Contents of Circular Linked List\n ";

printList(head);

return 0;

// This is code is contributed by rathbhupendra

Output:
Contents of Circular Linked List
11 2 56 12

// C program to implement
// the above approach
#include<stdio.h>
#include<stdlib.h>

/* structure for a node */


struct Node
{
int data;
struct Node *next;
};
/* Function to insert a node at the beginning of a Circular
linked list */
void push(struct Node **head_ref, int data)
{
struct Node *ptr1 = (struct Node *)malloc(sizeof(struct Node));
struct Node *temp = *head_ref;
ptr1->data = data;
ptr1->next = *head_ref;

/* If linked list is not NULL then set the next of last node */
if (*head_ref != NULL)
{
while (temp->next != *head_ref)
temp = temp->next;
temp->next = ptr1;
}
else
ptr1->next = ptr1; /*For the first node */

*head_ref = ptr1;
}

/* Function to print nodes in a given Circular linked list */


void printList(struct Node *head)
{
struct Node *temp = head;
if (head != NULL)
{
do
{
printf("%d ", temp->data);
temp = temp->next;
}
while (temp != head);
}
}

/* Driver program to test above functions */


int main()
{
/* Initialize lists as empty */
struct Node *head = NULL;

/* Created linked list will be 11->2->56->12 */


push(&head, 12);
push(&head, 56);
push(&head, 2);
push(&head, 11);

printf("Contents of Circular Linked List\n ");


printList(head);

return 0;
}

You might also like