Leetcode 92. Reverse Linked List II 翻轉部分連結串列
阿新 • • 發佈:2018-12-21
解決思路:
注意的要點是:m 可能位於頭結點,所以這裡臨時建立一個節點,每次將cur後面的節點放到pre節點後邊,這裡的cur->next
其實是在一直變化的,所以這裡cur並不用自己更新,每次進行重連結時相當於對連結串列進行了遍歷。
/** * 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) { ListNode* new_head = new ListNode(0); new_head->next = head; ListNode* pre = new_head; // 儲存m之前的節點 ListNode* cur = nullptr; for(int i = 0;i < m - 1; i++) //找到m之前的那個節點 pre = pre->next; cur = pre->next; for(int i = 0; i < n - m; i++) { ListNode* move = cur->next; cur->next = move->next; move->next = pre->next; pre->next = move; } return new_head->next; } };