Site icon T4Tutorials.com

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++:

#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.

 

 

Exit mobile version