> For the complete documentation index, see [llms.txt](https://soumyajit4419.gitbook.io/ds-algo/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://soumyajit4419.gitbook.io/ds-algo/linked-list/12.-reverse-linked-list-ii.md).

# 14. Reverse Linked List II

Reverse a linked list from position *m* to *n*. Do it in one-pass.

**Note:** 1 ≤ *m* ≤ *n* ≤ length of list.

**Example:**

```
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
```

## Solution:&#x20;

**Algorithm:**

<img src="https://leetcode.com/problems/reverse-linked-list-ii/Figures/92/iterative-2.png" alt="" data-size="original">                  ![](https://leetcode.com/problems/reverse-linked-list-ii/Figures/92/iterative-4.png)

```cpp
class Solution
{
public:
    ListNode *reverseBetween(ListNode *head, int m, int n)
    {

        if (m == n)
        {
            return head;
        }

        int i = 1;
        ListNode *p = head;
        ListNode *q = NULL;

        while (i != m)
        {
            q = p;
            p = p->next;
            i++;
        }

        ListNode *cur = p;
        ListNode *prev = q;
        ListNode *temp = p;

        i = 0;
        while (i <= n - m)
        {
            temp = temp->next;

            cur->next = prev;
            prev = cur;
            cur = temp;

            i++;
        }
        if (q == NULL)
        {
            head = prev;
        }
        else
        {
            q->next = prev;
        }

        p->next = cur;
        return head;
    }
};
```

**Time Complexity: O(n)**
