Reverse Linked List II

You are given the head of a singly linked list and two integers left and right with left <= right. Positions are 1-based: the head is at position 1.

Reverse the nodes from position left to position right, inclusive, leaving every other node where it is, and return the head of the list. Rewire the nodes rather than swapping their values.

Constraints

  • The list has n nodes, 1 <= n <= 500.
  • -500 <= Node.val <= 500
  • 1 <= left <= right <= n

Examples

Example 1

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

Positions 2 to 4 hold 2, 3, 4. Reversed they read 4, 3, 2; nodes 1 and 5 stay where they are.

Example 2

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

A one-node segment is already reversed.

Example 3

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

The segment is the whole list, and the head changes.

JavaScript you'll use: Linked list and tree nodes Destructuring, spread and rest

/**
 * Linked list nodes are provided (you don't need to define them):
 * class ListNode { constructor(val = 0, next = null) { this.val = val; this.next = next; } }
 */
/**
 * @param {ListNode} head
 * @param {number} left
 * @param {number} right
 * @return {ListNode}
 */
function reverseBetween(head, left, right) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.