Reverse Linked List II

MediumLinked List · In-place Reversal · Dummy Head🧩 Linked List TechniquesLeetCode #92 ↗Updated

Problem

Given the head of a singly linked list and two 1-based positions left ≤ right, reverse only the nodes from position left through position right, leaving everything before and after untouched. Return the head of the resulting list.
Inputhead = [1,2,3,4,5], left = 2, right = 4Output[1,4,3,2,5]
Inputhead = [5], left = 1, right = 1Output[5]

1 ≤ n ≤ 500  ·  -500 ≤ Node.val ≤ 500  ·  1 ≤ left ≤ right ≤ n  ·  Follow-up: do it in one pass.

Try it yourself

Java
class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Anchor at the node just before position left (a dummy covers left = 1). Then repeatedly take the node after the segment's original first node and move it to the front of the segment — after right - left moves the segment is reversed.
PatternLinked List Techniques

Instinct Nodes joined by next pointers and the task is to reverse, splice, merge, reorder or remove in place - grab a dummy head and rewire pointers carefully.

Memory hack Save next, flip, step - never let go of a rope before you've grabbed the next one.

Open the Linked List Techniques guide →

Approaches

Brute ForceCopy Values, Reverse the Sub-array

Time O(n)Space O(n)

Copy all values into a list, reverse the slice [left-1, right-1] with two pointers, then write the values back into the nodes in order. Correct because only the order of values matters for the output.

Java
public ListNode reverseBetween(ListNode head, int left, int right) {
    List<Integer> vals = new ArrayList<>();
    for (ListNode c = head; c != null; c = c.next) vals.add(c.val);
    for (int i = left - 1, j = right - 1; i < j; i++, j--) Collections.swap(vals, i, j);
    ListNode c = head;
    for (int v : vals) {
        c.val = v;
        c = c.next;
    }
    return head;
}

Easy, but needs O(n) memory and rewrites values rather than relinking nodes.

At a glance

LevelApproachTimeSpace
Brute ForceCopy Values, Reverse the Sub-arrayO(n)O(n)
BetterCut Out, Reverse, ReconnectO(n)O(1)
OptimalOne-Pass Front InsertionO(n)O(1)
Common pitfalls
  • Off-by-one when walking to before — positions are 1-based.
  • No dummy head — breaks when left = 1 because the head itself changes.
  • Forgetting to reconnect the segment's new tail to the rest of the list.
Interview tips
  • Draw the list with before and tail labelled; show one insertion.
  • Explain that tail never moves — the nodes move around it.
  • Test left = right, left = 1 and right = n.
Pattern
Dummy + front insertion → reverse a sub-range or k-sized groups of a linked list in one pass.
My notes saved in this browser