Skip to content

Reverse Linked List II

MediumLinked List
Decode it first. Clues, constraints, pattern and plan before any code.

You get the head of a linked list and two positions left and right, counted from 1. Reverse only the nodes from position left to position right, keep everything outside that stretch where it was, and return the head. Try to do it in one pass by relinking nodes.

1 -> 2 -> 3 -> 4 -> 5, left = 2, right = 4   →  1 -> 4 -> 3 -> 2 -> 5
5, left = 1, right = 1                       →  5
1 -> 2 -> 3, left = 1, right = 3             →  3 -> 2 -> 1

Constraints

  • 1 <= number of nodes <= 500
  • -500 <= Node.val <= 500
  • 1 <= left <= right <= number of nodes