# 92. Reverse Linked List II

## 1.問題

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

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-L_K6F9Qrhkrhg37yxdr%2F-L_K6IqW9IZaNc8H9Rwb%2Fimage.png?alt=media\&token=8192948e-77ae-48b6-9a2c-e38151070e87)

## 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;
    }
};
```
