The key difference is how the last node connects: in a circular linked list, it points back to the first node, forming a loop. In a linear linked list, the last node points to null, marking the end.
struct Node {
int data;
Node* next;
};
Node* head = new Node{1, nullptr};
Node* second = new Node{2, nullptr};
Node* third = new Node{3, nullptr};
head->next = second;
second->next = third;
third->next = head; // circular link
Node* current = head;
for (int i = 0; i < 5; i++) {
std::cout << current->data << " ";
current = current->next;
}The list has 3 nodes linked circularly. Traversing 5 nodes cycles through 1, 2, 3, then back to 1, then 2.
struct Node {
int data;
Node* next;
};
Node* head = new Node{10, nullptr};
Node* second = new Node{20, nullptr};
Node* third = new Node{30, nullptr};
head->next = second;
second->next = third;
third->next = second; // creates a loop
Node* current = head;
int count = 0;
while (current != nullptr && count < 6) {
std::cout << current->data << " ";
current = current->next;
count++;
}The last node points back to the second node, creating a loop between nodes 20 and 30. The loop prints 20 and 30 repeatedly until the count limit stops it.
Circular linked lists allow traversal to continue from any node indefinitely because the last node links back to the first, unlike linear lists which end at null.
struct Node {
int data;
Node* next;
};
Node* head = new Node{5, nullptr};
Node* second = new Node{10, nullptr};
Node* third = new Node{15, nullptr};
head->next = second;
second->next = third;
third->next = head; // bug here
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}The last node's next pointer points back to the head, making the list circular. The while loop never ends because current never becomes nullptr.
