# 20. \[Linked List] Reverse Linked List II

92\. Reverse Linked List IIMedium9.3K420Companies

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:**

![](https://assets.leetcode.com/uploads/2021/02/19/rev2ex2.jpg)

<pre><code><strong>Input: head = [1,2,3,4,5], left = 2, right = 4
</strong><strong>Output: [1,4,3,2,5]
</strong></code></pre>

**Example 2:**

<pre><code><strong>Input: head = [5], left = 1, right = 1
</strong><strong>Output: [5]
</strong></code></pre>

**Constraints:**

* The number of nodes in the list is `n`.
* `1 <= n <= 500`
* `-500 <= Node.val <= 500`
* `1 <= left <= right <= n`

**Follow up:** Could you do it in one pass?

{% embed url="<https://leetcode.com/problems/reverse-linked-list-ii/>" %}

> Time: O(N)

> Space: O(1)

```javascript
/**
 * 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}
 */
var reverseBetween = function(head, left, right) {
    if (left === right) 
        return head;

    const dummy = new ListNode(-1);
    dummy.next = head;

    let start = head;
    let end = head;

    let curr = dummy;
    let cnt = 0;
    while (curr !== null) {
        if (cnt === left - 1) {
            start = curr;
        }

        if (cnt === right) {
            end = curr;
        }

        curr = curr.next;
        cnt++;
    }

    let h = start.next;
    let t = end.next;
    curr = h;
    let prev = t;
    while (curr !== null && curr !== t) {
        const next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }

    start.next = prev;


    return dummy.next;
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/algorithm-problems/daily-algorithms/20.-linked-list-reverse-linked-list-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
