00:00

Reverse a Circular Linked List

Hello, In this tutorial, we will see how to reverse a circular linked list.

Let's first understand what a reversed list is, as given in the example below.

Example:

Reverse a Circular Linked List

Java program implementation of reverse a circular linked list

ReverseCLL.java
// Class representing a node in a circular linked list
class Node {
  public int data; // Store value of the node
  public Node next; // Store address of the next node

  // Constructor to initialize a node
  public Node(int data) {
    this.data = data;
    this.next = null;
  }
}

public class ReverseCLL {

  // Function to reverse the circular linked list
  static Node reverse(Node head_ref) {
    // if list is empty
    if (head_ref == null)
      return null;

    // reverse procedure same as reversing a
    // singly linked list
    Node prev = null;
    Node current = head_ref;
    Node next;
    do {
      next = current.next;
      current.next = prev;
      prev = current;
      current = next;
    } while (current != (head_ref));

    // adjusting the links so as to make the
    // last node point to the first node
    (head_ref).next = prev;
    head_ref = prev;
    return head_ref;
  }

  // Function to print circular linked list
  static void printList(Node head) {
    if (head == null)
      return;

    Node temp = head;
    do {
      System.out.print(temp.data + " ");
      temp = temp.next;
    } while (temp != head);
  }

  public static void main(String args[]) {
    // Create a circular linked list
    Node head = new Node(65);
    head.next = new Node(47);
    head.next.next = new Node(32);
    head.next.next.next = new Node(40);
    head.next.next.next.next = new Node(52);
    head.next.next.next.next.next = head;

    System.out.print("Original circular linked list: ");
    printList(head);

    head = reverse(head);

    System.out.print("\nReversed circular linked list: ");
    printList(head);
  }
}
Output
Original circular linked list: 65 47 32 40 52
Reversed circular linked list: 52 40 32 47 65

Time Complexity: O(n), here n represent the total number of nodes in a circular linked list.

Auxiliary Space: O(1)