700705. Rotate doubly Linked List

Easy

Rotate Doubly Linked List by P Nodes

Summary

Given a doubly linked list and an integer p, rotate the list to the right by p nodes. This problem involves manipulating a doubly linked list, where each node has references to both the previous (prev) and next (next) nodes.

Detailed Explanation

To solve this problem, we'll follow these steps:

  1. Initialize three pointers: current, prev_node, and new_tail. Set current to the head of the list.
  2. Move current p nodes to the right. If p is greater than the length of the list, move p % length nodes to the right (since rotating by the full length of the list is equivalent to not rotating at all).
  3. Update prev_node and new_tail accordingly:
    • Set prev_node to the node before current.
    • Set new_tail to the node after current.
  4. Update the next pointer of prev_node to point to new_tail. This effectively moves the tail of the list to the right by p nodes.
  5. Update the prev pointer of new_tail to point to prev_node. This sets the new head of the rotated list.

Here's a diagram illustrating the steps:

       +----+      +----+      +----+
       |  A  |     |  B  |     |  C  |
       +----+      +----+      +----+
           ^          ^          ^
           |          |          |
       +----+      +----+      +----+
       | prev_node |     | current |     | new_tail |
       +----+      +----+      +----+

In the diagram, A is the original head of the list, and C is the original tail. The rotation moves the tail to the right by 2 nodes.

Time complexity: O(n), where n is the length of the list. Space complexity: O(1), as we only use a few extra pointers.

Optimized Solutions

Java

View on GeeksforGeeks
public class DoublyLinkedList {
    public void rotate(int p) {
        if (head == null || head.next == null) return;

        Node current = head;
        for (int i = 0; i < p && current.next != null; i++) {
            current = current.next;
        }
        Node newTail = current;
        while (newTail.next != null) {
            newTail = newTail.next;
        }
        newTail.next = head;
        head.prev = newTail;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.