Reverse Linked List II

Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.

30:00

Reverse Linked List II
medium
Free written solution
Topics
Companies

Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.

Example 1:
Input: {"head":[1,2,3,4,5],"left":2,"right":4}
Output: [1,4,3,2,5]
Constraints:
  • The number of nodes in the list is nn.

  • 1≤n≤5001 \leq n \leq 500

  • −500≤Node.val≤500-500 \leq \text{Node.val} \leq 500

  • 1≤left≤right≤n1 \leq \text{left} \leq \text{right} \leq n

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"head":[1,2,3,4,5],"left":2,"right":4}

A dummy node goes in front of the head, so reversing from position 1 needs no special case. prev starts on the dummy.

▼ prev: fixed before the range▲ curr: first node, drifts back● nxt: jumps to the front
positions 2..4 · moves 0/2null0dummy12345prev

Moves to the front of the range

0/2

Following next from the dummy

[1, 2, 3, 4, 5]

Variables
VariableValue
left2
right4
prevdummy
currnull
nxtnull
moves0
DepthFunction Call
Stack empty
0/12