If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Here's a complete C++ implementation of a Circular Linked List:
cppCopy code
#include <iostream> class Node { public: int data; Node* next; Node(int data) : data(data), next(nullptr) {} }; class CircularLinkedList { private: Node* head; public: CircularLinkedList() : head(nullptr) {} ~CircularLinkedList() { if (head) { Node* current = head; do { Node* temp = current; current = current->next; delete temp; } while (current != head); } } void insertEnd(int data) { Node* newNode = new Node(data); if (!head) { head = newNode; head->next = head; // Make the only node point to itself } else { Node* current = head; while (current->next != head) { current = current->next; } current->next = newNode; newNode->next = head; // Make the new node point back to the head } } void display() { if (!head) { std::cout << "List is empty." << std::endl; return; } Node* current = head; do { std::cout << current->data << " -> "; current = current->next; } while (current != head); std::cout << "Head" << std::endl; } }; int main() { CircularLinkedList list; list.insertEnd(1); list.insertEnd(2); list.insertEnd(3); list.display(); // Output: 1 -> 2 -> 3 -> Head return 0; }In this implementation, we have a
Nodeclass representing each node in the circular linked list. TheCircularLinkedListclass contains aheadpointer, which points to the first node in the list.The
insertEndmethod is used to insert a new node at the end of the circular linked list. If the list is empty, the new node becomes the head, and it points to itself. If the list is not empty, we traverse to the last node and make it point to the new node, and the new node points back to the head.The
displaymethod is responsible for printing the elements of the circular linked list. It traverses through the list starting from the head node and continues until the current node points back to the head node, ensuring that we loop through the entire circular list once.In the
mainfunction, we demonstrate how to use theCircularLinkedListclass by creating a circular linked list, inserting elements, and then displaying the circular linked list.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support