[LeetCode] Reorder List 連結串列重排序
阿新 • • 發佈:2018-12-27
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
這道連結串列重排序問題可以拆分為以下三個小問題:
1. 使用快慢指標來找到連結串列的中點,並將連結串列從中點處斷開,形成兩個獨立的連結串列。
2. 將第二個鏈翻轉。
3. 將第二個連結串列的元素間隔地插入第一個連結串列中。
程式碼如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void reorderList(ListNode *head) { if (!head || !head->next || !head->next->next) return; ListNode *fast = head; ListNode *slow = head; while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; } ListNode *mid = slow->next; slow->next = NULL; ListNode*last = mid; ListNode *pre = NULL; while (last) { ListNode *next = last->next; last->next = pre; pre = last; last = next; } while (head && pre) { ListNode *next = head->next; head->next = pre; pre = pre->next; head->next->next = next; head = next; } } };