Circular linked list implementation in C++ (Doubly link list)
write a C++ program to demonstrate circular linked list with doubly link list
Here is an example of a circular doubly linked list implemented in C++:
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 94 95 96 97 98 99 100 101 102 103 104 |
#include <iostream> struct Node { int data; Node* next; Node* prev; }; // Function to create a new node Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->next = NULL; temp->prev = NULL; return temp; } // Function to create a circular doubly linked list // by connecting the last node to the head node void CircularDoubly(Node* head) { Node* current = head; while (current->next != NULL) { current = current->next; } current->next = head; head->prev = current; } // Function to print the circular doubly linked list void printList(Node* head) { Node* current = head; do { std::cout << current->data << " "; current = current->next; } while (current != head); } int main() { Node* head = newNode(9); head->next = newNode(8); head->next->next = newNode(7); head->next->next->next = newNode(6); CircularDoubly(head); std::cout << "Circular Doubly Linked List: "; printList(head); return 0; } |
output
Circular Doubly Linked List: 9 8 7 6
In this program, a Node structure is defined with data, next, and prev fields and a function newNode to create a new node with a specified data value.
The CircularDoubly function creates a circular doubly linked list by starting with a head node and connecting the last node in the list to the head node. The print list function traversing through the list, halting when it reaches the head node once more, and prints out the data values in the list (indicating the end of the list).
In the main, we create a linked list with four nodes and then make it circular by calling CircularDoubly. Finally, we print the list using the printlist.