LeetCode 92 · Linked list

Reverse Linked List II, explained with a picture

Reversing only part of a train.

Linked list
▶ Watch it step by step

The problem

Reverse only the part of a linked list from position left to position right (1-based).

Input:  1 → 2 → 3 → 4 → 5, left = 2, right = 4
Output: 1 → 4 → 3 → 2 → 5

Picture it

Picture a train where only a middle section is turned around. Walk to the coach just before the section. Then repeatedly take the coach right after the section’s first coach and move it to the front of the section.

Short version: the full lesson (brute force, complexity, edge cases and a quiz) is still being written. The animation is complete.

The key idea

One pass: “move next node to the front” right − left times. O(n).

Python solution

def reverse_between(head, left, right):
    dummy = Node(0, head)
    pre = dummy
    for _ in range(left - 1):
        pre = pre.next
    curr = pre.next
    for _ in range(right - left):
        nxt = curr.next
        curr.next = nxt.next
        nxt.next = pre.next
        pre.next = nxt
    return dummy.next

In the interactive version each line lights up as the animation runs, and you can type your own input to see the algorithm handle it.