00:00

Reverse a Circular Linked List

Last updated:

Reversing a circular linked list changes the direction of the ring: after the reversal, following next visits the nodes in the opposite order, and the old last node becomes the new head.

The method is the same three-pointer technique used for a singly linked list, with two changes: the loop stops when it comes back to the head instead of at null, and at the end the old head (now the last node) must be linked to the new head so that the list stays circular. It takes O(n) time and O(1) extra space.

Example:

A circular linked list before and after reversal

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
  // Reverses the ring and returns the new head
  static Node reverse(Node head) {
    if (head == null) {
      return null;
    }

    Node prev = null;
    Node current = head;
    Node next;

    // Turn every next link around, going once round the ring
    do {
      next = current.next;
      current.next = prev;
      prev = current;
      current = next;
    } while (current != head);

    // The old head is now the last node: close the ring
    head.next = prev;

    // prev is the old last node, which is the new head
    return prev;
  }

  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), where n is the number of nodes.

Extra Space: O(1)