3_circular linked list
3_circular linked list
In a circular doubly linked list, each node has two pointers ( next and prev ), just
like in a regular doubly linked list, but the difference is that:
1. The next pointer of the last node points to the head node.
2. The prev pointer of the head node points to the last node.
This creates a circular structure, allowing traversal from any node in a continuous
loop in either direction.
public CircularDoublyLinkedList() {
head = null;
tail = null;
}
if (head == null) {
head = tail = newNode;
head.next = head;
head.prev = head;
} else {
newNode.next = head;
newNode.prev = tail;
head.prev = newNode;
tail.next = newNode;
head = newNode;
}
}
if (tail == null) {
head = tail = newNode;
head.next = head;
head.prev = head;
} else {
newNode.prev = tail;
newNode.next = head;
tail.next = newNode;
head.prev = newNode;
tail = newNode;
}
}
// Display forward
public void displayForward() {
if (head == null) return;
// Display backward
public void displayBackward() {
if (tail == null) return;
// Node class
private static class Node {
int data;
Node next;
Node prev;
Key Operations
Deletion from the beginning and end: Updates head , tail , and adjusts the
circular references.
2. How would you detect if a linked list is circular (circular singly or doubly)?
3. When would you use a circular doubly linked list over other linked list types?
4. How can you implement a circular linked list in a real-world application, like
a playlist or a round-robin scheduler?
5. How would you find the middle element in a circular linked list?
6. Can you implement a queue using a circular doubly linked list? How?