Circular linked list
Circular Linked List A circular linked list is a type of linked list in which each node points to the next node in the linked list, with the last node refer...
Circular Linked List A circular linked list is a type of linked list in which each node points to the next node in the linked list, with the last node refer...
Circular Linked List
A circular linked list is a type of linked list in which each node points to the next node in the linked list, with the last node referencing the first node. This creates a circular loop.
The head pointer of the circular linked list points to the first node in the linked list, and the tail pointer points to the last node in the linked list. This way, the first and last nodes are always connected.
Advantages of Circular Linked List:
Circular data structure: The list can be viewed from any node, allowing for efficient random access to any node in the linked list.
No need to iterate through the entire list: Once the head reaches the end of the linked list, the head can be easily updated to point to the first node.
Efficient searching and sorting: Searching and sorting are very efficient in circular linked lists because the nodes can be accessed directly from any node in the list.
Disadvantages of Circular Linked List:
Memory waste: Circular linked lists require more memory than linear linked lists to store the same amount of data, as they need to store pointers to the next and previous nodes.
Time complexity: Accessing a node in a circular linked list can be slower than accessing a node in a linear linked list, as the head pointer needs to traverse the entire list to reach the desired node.
Potential for memory leaks: If not handled properly, circular linked lists can lead to memory leaks, where the memory allocated for the first node is not released when the list is no longer used.
Examples of Circular Linked List:
c++
struct Node {
int data;
Node* next;
Node* prev;
};
Node* head;
python
class Node:
def init(self, data):
self.data = data
self.next = None
self.prev = None
head = Node(1)
current = head
while current:
print(current.data, end=" ")
current = current.next
if current == head:
head = head.next
+----------+
| Head --> |
+----------+
| |
+----------+
| Current --> |
+----------+
| Tail --> |
+----------+