92. Reverse Linked List II

1.問題

  • 反轉linked list m~n的順序

2.想法

  • 提問

  • function header, parameter

  • test input

  • 說明想法

    • 讓*pre為開始反轉的前一個指標

    • *cur為開始反轉的第一個指標

  • 測試計算複雜度: 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;
    }
};

Last updated