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

# 92. Reverse Linked List II

## 1.問題

* 反轉linked list m\~n的順序

![](/files/-L_K6IqW9IZaNc8H9Rwb)

## 2.想法

* 提問
* function header, parameter
* test input
* 說明想法
  * 讓\*pre為開始反轉的前一個指標
  * \*cur為開始反轉的第一個指標&#x20;
* 測試計算複雜度: O(n^2) ?

## 3.程式碼

```
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        if (m < 1 || m >= n || !head) {
            return head;
        }
        
        ListNode *newNode = new ListNode(0);
        newNode->next = head;
        head = newNode;
        
        for (int i = 0; i < m - 1; i++) {
            head = head->next;
        }
        ListNode *pre = head->next, *cur = pre->next;
        
        for (int i = 0; i < n - m; i++) {
            ListNode *next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        
        head->next->next = cur;
        head->next = pre;
        return newNode->next;
    }
};
```
