diff --git a/circular_linked_list.cpp b/circular_linked_list.cpp new file mode 100644 index 0000000..d09b6eb --- /dev/null +++ b/circular_linked_list.cpp @@ -0,0 +1,88 @@ +#include +using namespace std; + +class Node{ + public: + int data; + Node* next; + Node(int data){ + this ->data= data; + next = NULL; + } +}; + +class LinkedList { +public: + Node* head; + + LinkedList() { + head = NULL; + } + + // Function to insert node at the end of the singly linked list + void insert(int value) { + Node* newNode = new Node(value); + + if (head == NULL) { + head = newNode; + return; + } + + Node* temp = head; + while (temp->next != NULL) { + temp = temp->next; + } + temp->next = newNode; + } + + // Convert singly linked list to circular linked list + void convertToCircular() { + if (head == NULL) return; + + Node* temp = head; + + // Traverse till the last node + while (temp->next != NULL) { + temp = temp->next; + } + + // Make it circular + temp->next = head; + } + + // Display function for circular linked list (print limited nodes to avoid infinite loop) + void displayCircular(int limit = 10) { + if (head == NULL) { + cout << "List is empty\n"; + return; + } + + Node* temp = head; + int count = 0; + + while (temp != NULL && count < limit) { + cout << temp->data << " -> "; + temp = temp->next; + count++; + } + cout << "(back to head...)\n"; + } +}; + +int main() { + LinkedList list; + + // Insert values + list.insert(10); + list.insert(20); + list.insert(30); + list.insert(40); + + cout << "Converting to Circular Linked List...\n"; + list.convertToCircular(); + + // Display circular list (limited to avoid infinite loop) + list.displayCircular(10); + + return 0; +}