Reverse Linked List II

Medium#92reverse

You get a linked list and two positions, left and right, counted from 1. Reverse only the nodes from position left to position right, keep the rest as it is, and return the head. Our example: 3 → 8 → 1 → 6 → 4 → 2, left = 2, right = 5 — the answer is 3 → 4 → 6 → 1 → 8 → 2.

input
head: the head of a linked list of n nodes; left, right: positions in it, counted from 1.
returns
The head of the list with its nodes from position left to position right reversed.
constraints
  • 1 ≤ n ≤ 500
  • −500 ≤ Node.val ≤ 500
  • 1 ≤ left ≤ right ≤ n
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} left
 * @param {number} right
 * @return {ListNode}
 */
function reverseBetween(head, left, right) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more linked list pointers problems

Pattern “Linked list pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.