Skip to content
Onsite

Reverse Linked List II

MediumP2Coding

Given the head of a singly linked list and two 1-based positions left <= right, reverse the nodes from position left to position right and return the head of the resulting list. A list node has val and next. The ListNode class is already defined for you.

Try to do it in one pass.

Example 1

Input
head = [1,2,3,4,5], left = 2, right = 4
Output
[1,4,3,2,5]

Example 2

Input
head = [5], left = 1, right = 1
Output
[5]

Example 3

Input
head = [1,2,3], left = 1, right = 3
Output
[3,2,1]

Constraints

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

Hints

Run checks the 3 visible tests, Submit all 10.