text: Reverse a doubly circular linked list | C ++ implementation to revesre a doubly circular linked list ; structure of a node of linked list ; function to create and return a new node ; Function to insert at the end ; If the list is empty , create a single node circular and doubly list ; Find last node ; Start is going to be next of new_node ; Make new node previous of start ; Make last preivous of new node ; Make new node next of old last ; Uitlity function to revesre a doubly circular linked list ; Initialize a new head pointer ; get pointer to the the last node ; set ' curr ' to last node ; traverse list in backward direction ; insert ' curr ' at the end of the list starting with the ' new _ head ' pointer ; head pointer of the reversed list ; function to display a doubly circular list in forward and backward direction ; Driver program to test above
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next , * prev ; } ; Node * getNode ( int data ) { Node * newNode = ( Node * ) malloc ( sizeof ( Node ) ) ; newNode -> data = data ; return newNode ; } void insertEnd ( Node * * head , Node * new_node ) { if ( * head == NULL ) { new_node -> next = new_node -> prev = new_node ; * head = new_node ; return ; } Node * last = ( * head ) -> prev ; new_node -> next = * head ; ( * head ) -> prev = new_node ; new_node -> prev = last ; last -> next = new_node ; } Node * reverse ( Node * head ) { if ( ! head ) return NULL ; Node * new_head = NULL ; Node * last = head -> prev ; Node * curr = last , * prev ; while ( curr -> prev != last ) { prev = curr -> prev ; insertEnd ( & new_head , curr ) ; curr = prev ; } insertEnd ( & new_head , curr ) ; return new_head ; } void display ( Node * head ) { if ( ! head ) return ; Node * temp = head ; cout << " Forward ▁ direction : ▁ " ; while ( temp -> next != head ) { cout << temp -> data << " ▁ " ; temp = temp -> next ; } cout << temp -> data ; Node * last = head -> prev ; temp = last ; cout << " Backward direction : " while ( temp -> prev != last ) { cout << temp -> data << " ▁ " ; temp = temp -> prev ; } cout << temp -> data ; } int main ( ) { Node * head = NULL ; insertEnd ( & head , getNode ( 1 ) ) ; insertEnd ( & head , getNode ( 2 ) ) ; insertEnd ( & head , getNode ( 3 ) ) ; insertEnd ( & head , getNode ( 4 ) ) ; insertEnd ( & head , getNode ( 5 ) ) ; cout << " Current ▁ list : STRNEWLINE " ; display ( head ) ; head = reverse ( head ) ; cout << " Reversed list : " display ( head ) ; return 0 ; }