Circular LinkedList
Circular LinkedList
#include <iostream>
using namespace std;
// Node structure
struct Node {
int data;
Node* next;
};
if (head == nullptr) {
newNode->next = newNode; // First node points to itself
head = newNode;
} else {
Node* temp = head;
while (temp->next != head) { // Traverse to the last node
temp = temp->next;
}
temp->next = newNode;
newNode->next = head; // Maintain circular property
}
}
insertAtTail(head, 10);
insertAtTail(head, 20);
insertAtTail(head, 30);
insertAtHead(head, 5);
return 0;
}
1. Node Structure:
o Each Node contains data and a pointer to the next node.
o For a circular linked list, the last node’s next pointer points back to the head node.
2. Insert at Head:
o Adds a new node at the beginning of the list.
o If the list is empty, the node points to itself.
o If the list is non-empty, we update the pointers to maintain the circular property.
3. Insert at Tail:
o Adds a new node at the end of the list.
o Handles both the empty and non-empty list cases, ensuring the new node points to the
head.
4. Delete a Node:
o Searches for a node with the given value and deletes it.
o Special care is taken for deleting the head node or when the list has only one element.
5. Display Function:
o Traverses the circular linked list, printing all elements until it circles back to the head.
6. Search Function:
o Searches for a specific value in the list, returning true if found, false otherwise.
7. Main Function:
o Demonstrates how to use the above operations by creating a list, displaying it, and
performing insertions, deletions, and searches.
Sample Output: