The Wayback Machine - https://web.archive.org/web/20240704221005/https://www.geeksforgeeks.org/reverse-a-doubly-circular-linked-list/
Open In App

Reverse a doubly circular linked list

Last Updated : 01 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:

C++




// C++ implementation to reverse a
// doubly circular linked list
#include <bits/stdc++.h>
 
using namespace std;
 
// structure of a node of linked list
struct Node {
    int data;
    Node *next, *prev;
};
 
// function to create and return a new node
Node* getNode(int data)
{
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    return newNode;
}
 
// Function to insert at the end
void insertEnd(Node** head, Node* new_node)
{
    // If the list is empty, create a single node
    // circular and doubly list
    if (*head == NULL) {
        new_node->next = new_node->prev = new_node;
        *head = new_node;
        return;
    }
 
    // If list is not empty
 
    /* Find last node */
    Node* last = (*head)->prev;
 
    // Start is going to be next of new_node
    new_node->next = *head;
 
    // Make new node previous of start
    (*head)->prev = new_node;
 
    // Make last previous of new node
    new_node->prev = last;
 
    // Make new node next of old last
    last->next = new_node;
}
 
// Utility function to reverse a
// doubly circular linked list
Node* reverse(Node* head)
{
    if (!head)
        return NULL;
 
    // Initialize a new head pointer
    Node* new_head = NULL;
 
    // get pointer to the last node
    Node* last = head->prev;
 
    // set 'curr' to last node
    Node *curr = last, *prev;
 
    // traverse list in backward direction
    while (curr->prev != last) {
        prev = curr->prev;
 
        // insert 'curr' at the end of the list
        // starting with the 'new_head' pointer
        insertEnd(&new;_head, curr);
        curr = prev;
    }
    insertEnd(&new;_head, curr);
 
    // head pointer of the reversed list
    return new_head;
}
 
// function to display a doubly circular list in
// forward and backward direction
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 << "\nBackward direction: ";
    while (temp->prev != last) {
        cout << temp->data << " ";
        temp = temp->prev;
    }
    cout << temp->data;
}
 
// Driver program to test above
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:\n";
    display(head);
 
    head = reverse(head);
 
    cout << "\n\nReversed list:\n";
    display(head);
 
    return 0;
}


Java




// Java implementation to reverse a
// doubly circular linked list
class GFG
{
 
// structure of a node of linked list
static class Node
{
    int data;
    Node next, prev;
};
 
// function to create and return a new node
static Node getNode(int data)
{
    Node newNode = new Node();
    newNode.data = data;
    return newNode;
}
 
// Function to insert at the end
static Node insertEnd(Node head, Node new_node)
{
    // If the list is empty, create a single node
    // circular and doubly list
    if (head == null)
    {
        new_node.next = new_node.prev = new_node;
        head = new_node;
        return head;
    }
 
    // If list is not empty
 
    // Find last node /
    Node last = (head).prev;
 
    // Start is going to be next of new_node
    new_node.next = head;
 
    // Make new node previous of start
    (head).prev = new_node;
 
    // Make last previous of new node
    new_node.prev = last;
 
    // Make new node next of old last
    last.next = new_node;
    return head;
}
 
// Utility function to reverse a
// doubly circular linked list
static Node reverse(Node head)
{
    if (head==null)
        return null;
 
    // Initialize a new head pointer
    Node new_head = null;
 
    // get pointer to the last node
    Node last = head.prev;
 
    // set 'curr' to last node
    Node curr = last, prev;
 
    // traverse list in backward direction
    while (curr.prev != last)
    {
        prev = curr.prev;
 
        // insert 'curr' at the end of the list
        // starting with the 'new_head' pointer
        new_head=insertEnd(new_head, curr);
        curr = prev;
    }
    new_head=insertEnd(new_head, curr);
 
    // head pointer of the reversed list
    return new_head;
}
 
// function to display a doubly circular list in
// forward and backward direction
static void display(Node head)
{
    if (head==null)
        return;
 
    Node temp = head;
 
    System.out.print( "Forward direction: ");
    while (temp.next != head)
    {
        System.out.print( temp.data + " ");
        temp = temp.next;
    }
        System.out.print( temp.data + " ");
 
    Node last = head.prev;
    temp = last;
 
    System.out.print( "\nBackward direction: ");
    while (temp.prev != last)
    {
        System.out.print( temp.data + " ");
        temp = temp.prev;
    }
        System.out.print( temp.data + " ");
}
 
// Driver code
public static void main(String args[])
{
    Node head = null;
 
    head =insertEnd(head, getNode(1));
    head =insertEnd(head, getNode(2));
    head =insertEnd(head, getNode(3));
    head =insertEnd(head, getNode(4));
    head =insertEnd(head, getNode(5));
 
    System.out.print( "Current list:\n");
    display(head);
 
    head = reverse(head);
 
    System.out.print( "\n\nReversed list:\n");
    display(head);
}
}
 
// This code is contributed by Arnab Kundu


Python3




# Python3 implementation to reverse a
# doubly circular linked list
import math
 
# structure of a node of linked list
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
# function to create and return a new node
def getNode(data):
    newNode = Node(data)
    newNode.data = data
    return newNode
 
# Function to insert at the end
def insertEnd(head, new_node):
     
    # If the list is empty, create a single node
    # circular and doubly list
    if (head == None) :
        new_node.next = new_node
        new_node.prev = new_node
        head = new_node
        return head
     
    # If list is not empty
 
    # Find last node
    last = head.prev
 
    # Start is going to be next of new_node
    new_node.next = head
 
    # Make new node previous of start
    head.prev = new_node
 
    # Make last previous of new node
    new_node.prev = last
 
    # Make new node next of old last
    last.next = new_node
    return head
 
# Utility function to reverse a
# doubly circular linked list
def reverse(head):
    if (head == None):
        return None
 
    # Initialize a new head pointer
    new_head = None
 
    # get pointer to the last node
    last = head.prev
 
    # set 'curr' to last node
    curr = last
    #*prev
 
    # traverse list in backward direction
    while (curr.prev != last):
        prev = curr.prev
 
        # insert 'curr' at the end of the list
        # starting with the 'new_head' pointer
        new_head = insertEnd(new_head, curr)
        curr = prev
     
    new_head = insertEnd(new_head, curr)
 
    # head pointer of the reversed list
    return new_head
 
# function to display a doubly circular list in
# forward and backward direction
def display(head):
    if (head == None):
        return
     
    temp = head
 
    print("Forward direction: ", end = "")
    while (temp.next != head):
        print(temp.data, end = " ")
        temp = temp.next
     
    print(temp.data)
 
    last = head.prev
    temp = last
 
    print("Backward direction: ", end = "")
    while (temp.prev != last):
        print(temp.data, end = " ")
        temp = temp.prev
     
    print(temp.data)
 
# Driver Code
if __name__=='__main__':
 
    head = None
 
    head = insertEnd(head, getNode(1))
    head = insertEnd(head, getNode(2))
    head = insertEnd(head, getNode(3))
    head = insertEnd(head, getNode(4))
    head = insertEnd(head, getNode(5))
 
    print("Current list:")
    display(head)
 
    head = reverse(head)
 
    print("\nReversed list:")
    display(head)
 
# This code is contributed by Srathore


C#




// C# implementation to reverse a
// doubly circular linked list
using System;
 
class GFG
{
 
// structure of a node of linked list
public class Node
{
    public int data;
    public Node next, prev;
};
 
// function to create and return a new node
static Node getNode(int data)
{
    Node newNode = new Node();
    newNode.data = data;
    return newNode;
}
 
// Function to insert at the end
static Node insertEnd(Node head, Node new_node)
{
    // If the list is empty, create a single node
    // circular and doubly list
    if (head == null)
    {
        new_node.next = new_node.prev = new_node;
        head = new_node;
        return head;
    }
 
    // If list is not empty
 
    // Find last node /
    Node last = (head).prev;
 
    // Start is going to be next of new_node
    new_node.next = head;
 
    // Make new node previous of start
    (head).prev = new_node;
 
    // Make last previous of new node
    new_node.prev = last;
 
    // Make new node next of old last
    last.next = new_node;
    return head;
}
 
// Utility function to reverse a
// doubly circular linked list
static Node reverse(Node head)
{
    if (head == null)
        return null;
 
    // Initialize a new head pointer
    Node new_head = null;
 
    // get pointer to the last node
    Node last = head.prev;
 
    // set 'curr' to last node
    Node curr = last, prev;
 
    // traverse list in backward direction
    while (curr.prev != last)
    {
        prev = curr.prev;
 
        // insert 'curr' at the end of the list
        // starting with the 'new_head' pointer
        new_head=insertEnd(new_head, curr);
        curr = prev;
    }
    new_head=insertEnd(new_head, curr);
 
    // head pointer of the reversed list
    return new_head;
}
 
// function to display a doubly circular list in
// forward and backward direction
static void display(Node head)
{
    if (head == null)
        return;
 
    Node temp = head;
 
    Console.Write( "Forward direction: ");
    while (temp.next != head)
    {
        Console.Write( temp.data + " ");
        temp = temp.next;
    }
        Console.Write( temp.data + " ");
 
    Node last = head.prev;
    temp = last;
 
    Console.Write( "\nBackward direction: ");
    while (temp.prev != last)
    {
        Console.Write( temp.data + " ");
        temp = temp.prev;
    }
        Console.Write( temp.data + " ");
}
 
// Driver code
public static void Main(String []args)
{
    Node head = null;
 
    head = insertEnd(head, getNode(1));
    head = insertEnd(head, getNode(2));
    head = insertEnd(head, getNode(3));
    head = insertEnd(head, getNode(4));
    head = insertEnd(head, getNode(5));
 
    Console.Write( "Current list:\n");
    display(head);
 
    head = reverse(head);
 
    Console.Write( "\n\nReversed list:\n");
    display(head);
}
}
 
// This code contributed by Rajput-Ji


Javascript




<script>
 
      // JavaScript implementation to reverse a
      // doubly circular linked list
      // structure of a node of linked list
      class Node {
        constructor() {
          this.data = 0;
          this.next = null;
          this.prev = null;
        }
      }
 
      // function to create and return a new node
      function getNode(data) {
        var newNode = new Node();
        newNode.data = data;
        return newNode;
      }
 
      // Function to insert at the end
      function insertEnd(head, new_node) {
        // If the list is empty, create a single node
        // circular and doubly list
        if (head == null) {
          new_node.next = new_node.prev = new_node;
          head = new_node;
          return head;
        }
 
        // If list is not empty
 
        // Find last node /
        var last = head.prev;
 
        // Start is going to be next of new_node
        new_node.next = head;
 
        // Make new node previous of start
        head.prev = new_node;
 
        // Make last previous of new node
        new_node.prev = last;
 
        // Make new node next of old last
        last.next = new_node;
        return head;
      }
 
      // Utility function to reverse a
      // doubly circular linked list
      function reverse(head) {
        if (head == null) return null;
 
        // Initialize a new head pointer
        var new_head = null;
 
        // get pointer to the last node
        var last = head.prev;
 
        // set 'curr' to last node
        var curr = last,
          prev;
 
        // traverse list in backward direction
        while (curr.prev != last) {
          prev = curr.prev;
 
          // insert 'curr' at the end of the list
          // starting with the 'new_head' pointer
          new_head = insertEnd(new_head, curr);
          curr = prev;
        }
        new_head = insertEnd(new_head, curr);
 
        // head pointer of the reversed list
        return new_head;
      }
 
      // function to display a doubly circular list in
      // forward and backward direction
      function display(head) {
        if (head == null) return;
 
        var temp = head;
 
        document.write("Forward direction: ");
        while (temp.next != head) {
          document.write(temp.data + " ");
          temp = temp.next;
        }
        document.write(temp.data + " ");
 
        var last = head.prev;
        temp = last;
 
        document.write("<br>Backward direction: ");
        while (temp.prev != last) {
          document.write(temp.data + " ");
          temp = temp.prev;
        }
        document.write(temp.data + " ");
      }
 
      // Driver code
      var head = null;
 
      head = insertEnd(head, getNode(1));
      head = insertEnd(head, getNode(2));
      head = insertEnd(head, getNode(3));
      head = insertEnd(head, getNode(4));
      head = insertEnd(head, getNode(5));
 
      document.write("Current list:<br>");
      display(head);
 
      head = reverse(head);
 
      document.write("<br><br>Reversed list:<br>");
      display(head);
       
</script>


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.


Similar Reads

Applications, Advantages and Disadvantages of Circular Doubly Linked List
The circular doubly linked list is a combination of the doubly linked list and the circular linked list. It means that this linked list is bidirectional and contains two pointers and the last pointer points to the first pointer. Applications of Circular Doubly Linked List: Music and video playlists: Circular doubly linked lists are commonly used to
4 min read
Convert an Array to a Circular Doubly Linked List
Prerequisite: Doubly Linked list, Circular Linked List, Circular Doubly Linked ListGiven an array of N elements. The task is to write a program to convert the array into a circular doubly linked list. The idea is to start traversing the array and for every array element create a new list node and assign the prev and next pointers of this node accor
8 min read
Search an Element in Doubly Circular Linked List
Pre-requisite: Convert an Array to a Circular Doubly Linked List, Doubly Circular Linked ListGiven a doubly circular linked list. The task is to find the position of an element in the list. Image Representation: Algorithm: Declare a temp pointer, and initialize it to the head of the list.Iterate the loop until temp reaches the start address (last n
13 min read
Remove all even parity nodes from a Doubly and Circular Singly Linked List
Given a Doubly linked list and Circular singly linked list containing N nodes, the task is to remove all the nodes from each list which contains elements whose parity is even. Example: Input: CLL = 9 -&gt; 11 -&gt; 34 -&gt; 6 -&gt; 13 -&gt; 21 Output: 11 -&gt; 13 -&gt; 21 Explanation: The circular singly linked list contains : 11 -&gt; 1011, parity
15+ min read
Modify a Circular Doubly Linked List such that each node stores the sum of all nodes except itself
Given a circular doubly linked list consisting of N nodes, the task is to modify every node of the given Linked List such that each node contains the sum of all nodes except that node. Examples: Input: 4 ↔ 5 ↔ 6 ↔7 ↔ 8Output: 26 ↔ 25 ↔ 24 ↔ 23 ↔ 22Explanation:1st Node: Sum of all nodes except itself = (5 + 6 + 7 + 8) = 26.2nd Node: Sum of all nodes
15+ min read
Insertion at Specific Position in a Circular Doubly Linked List
Prerequisite: Insert Element Circular Doubly Linked List.Convert an Array to a Circular Doubly Linked List.Given the start pointer pointing to the start of a Circular Doubly Linked List, an element and a position. The task is to insert the element at the specified position in the given Circular Doubly Linked List. Recommended: Please try your appro
15+ min read
Introduction to Circular Doubly Linked List
A circular doubly linked list is defined as a circular linked list in which each node has two links connecting it to the previous node and the next node. Characteristics of Circular Doubly Linked List :A circular doubly linked list has the following properties: Circular: A circular doubly linked list's main feature is that it is circular in design.
4 min read
Insertion in Doubly Circular Linked List
Circular Doubly Linked List has properties of both doubly linked list and circular linked list in which two consecutive elements are linked or connected by the previous and next pointer and the last node points to the first node by the next pointer and also the first node points to the last node by the previous pointer. Following is the representat
15+ min read
Deletion in Doubly Circular Linked List
We have discussed the doubly circular linked list introduction and its insertion.Let us formulate the problem statement to understand the deletion process. Given a ‘key’, delete the first occurrence of this key in the circular doubly linked list. Algorithm: Case 1: Empty List(start = NULL) If the list is empty, simply return it. Case 2: The List in
15+ min read
Circular Linked List Implementation of Circular Queue
Prerequisite – Circular Singly Linked List We have discussed basics and how to implement circular queue using array in set 1. Circular Queue | Set 1 (Introduction and Array Implementation) In this post another method of circular queue implementation is discussed, using Circular Singly Linked List. Operations on Circular Queue: Front:Get the front i
9 min read
three90RightbarBannerImg