Circular LInked List
Circular LInked List
sharmaharshvardhan80@gmail.com
What is Circular Linked List?
The circular linked list is a linked list in which all nodes form a circle. The initial and
last nodes in a circular linked list are linked to each other, forming a circle. There is no
NULL at the end.
● Doubly Linked List: Circular Doubly Linked List has properties of both doubly
linked list and circular linked list in which two consecutive elements are linked
or connected by the previous. Next, pointer and the last node points to the first
node by the next pointer and the first node points to the last node by the
previous pointer.
sharmaharshvardhan80@gmail.com
public Node(int data) {
this.data = data;
}
}
We can do some operations on the circular linked list similar to the singly
linked list which are:
1. Insertion
2. Deletion
=> Store the address of the current first node in the newNode (i.e. directing
the newNode to the current first node) point the last node to the newNode
(i.e making newNode as head)
sharmaharshvardhan80@gmail.com
2. Insertion between two nodes
=> Insert newNode after the first node.travel to the supplied node (let this
node be p) direct the next of newNode to the node next to p put the address
of newNode at next of p.
=> Insert the address of the head node to the next of newNode (making
newNode the last node) make newNode the final node by pointing the
current last node to newNode.
sharmaharshvardhan80@gmail.com
Deletion in a Circular Linked List
sharmaharshvardhan80@gmail.com
class Solution {
static class Node {
int data;
Node next;
};
sharmaharshvardhan80@gmail.com
static Node addAfter(Node last, int data, int item) {
if (last == null)
return null;
Node newNode, p;
p = last.next;
do {
if (p.data == item) {
newNode = new Node();
newNode.data = data;
newNode.next = p.next;
p.next = newNode;
if (p == last)
last = newNode;
return last;
}
p = p.next;
} while (p != last.next);
System.out.println(item + "The given node is not present in the list");
return last;
}
sharmaharshvardhan80@gmail.com
}
while (temp.next != last && temp.next.data != key) {
temp = temp.next;
}
if (temp.next.data == key) {
d = temp.next;
temp.next = d.next;
}
return last;
}
sharmaharshvardhan80@gmail.com
Thanks for reading this article till the end.