VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-a-doubly-circular-linked-list/

⇱ Reverse a doubly circular linked list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse a doubly circular linked list

Last Updated : 1 Sep, 2022

The problem is to reverse the given doubly circular linked list.

Examples: 

Input: 

👁 Doubly circular linked list

Output:  

👁 Reverse doubly circular linked list

Algorithm:  

insertEnd(head, new_node) 
 Declare last

 if head == NULL then
 new_node->next = new_node->prev = new_node
 head = new_node
 return 
 
 last = head->prev
 new_node->next = head 
 head->prev = new_node
 new_node->prev = last 
 last->next = new_node

reverse(head)
 Initialize new_head = NULL
 Declare last
 
 last = head->prev
 Initialize curr = last, prev
 
 while curr->prev != last
 prev = curr->prev
 insertEnd(&new_head, curr)
 curr = prev
 insertEnd(&new_head, curr)
 
 return new_head

Explanation: The variable head in the parameter list of insertEnd() is a pointer to a pointer variable. reverse() traverses the doubly circular linked list starting with the head pointer in the backward direction and one by one gets the node in the traversal. It inserts those nodes at the end of the list that starts with the new_head pointer with the help of the function insertEnd() and finally returns the new_head

Implementation:


Output
Current list:
Forward direction: 1 2 3 4 5
Backward direction: 5 4 3 2 1

Reversed list:
Forward direction: 5 4 3 2 1
Backward direction: 1 2 3 4 5

Complexity Analysis:

  • Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list.
  • Auxiliary Space: O(1), as we are not using any extra space.
Comment