Circular linked list implementation in C++ (Singly)
write a C++ program to demonstrate circular linked list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
#include <iostream> struct Node { int data; Node* next; }; // User define function to create a new node Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->next = NULL; return temp; } // User define function to create a circular linked list void CircularImplementation(Node* head) { Node* current = head; while (current->next != NULL) { current = current->next; } current->next = head; } // User define function to print the circular linked list void printList(Node* head) { Node* current = head; do { std::cout << current->data << " "<<endl; current = current->next; } while (current != head); } int main() { Node* head = newNode(7); head->next = newNode(4); head->next->next = newNode(9); head->next->next->next = newNode(2); CircularImplementation(head); std::cout << "Circular Linked List: "<<endl; printList(head); return 0; } |
Explanation
- A Node structure with data and next
- A User define function newNode to create a new node with a given data value.
- The CircularImplementation User define function takes a head node and It forms a circular linked list by joining the final node in the list to the head node.
- The printList User define function prints out the data values in the list by traversing the list and pausing when it hits the head node once more. In main, we create a linked list with four nodes and then make it circular by calling CircularImplementation.
- Finally, we print the list using printList.
The output of this program will be:
Circular Linked List: 7 4 9 2