# 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

```java
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null || head.next == null || m >= n) {
           return head; 
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        for (int i = 1; i < m; i++) {
            if (head == null) {
                return null;
            }
            head = head.next;
        } 
        ListNode prevNode = head;
        ListNode tailNode = head.next;
        ListNode curr = head.next;
        prevNode.next = null;
        for (int i = m; i <= n; i++) {
            if (i == n) {
               tailNode.next = curr.next; 
            }
            ListNode nextNode = curr.next;    
            curr.next = prevNode.next;
            prevNode.next = curr;
            curr = nextNode;
        }
        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://aaronice.gitbook.io/lintcode/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.
