143. Reorder List
143. Reorder List
題意
給定一個 linked list
將 →
→ … →
→
改為 →
→
→
→
→
→ …
限制
-
The number of nodes in the list is in the range
[1, 5 * 10^4]
. -
1 <= Node.val <= 1000
思考
-
額外用陣列儲存每個節點後按 index 重新排列,可用
O(n)
Space complexity 完成 -
若要 inplace 的完成 reorder
-
找出中心點,分為兩半 ⇒ 快慢指標
-
將右半邊的 linked list 反過來
-
合併兩條 linked list
-
Solution
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
ListNode* reverse(ListNode* head) {
auto node = head;
ListNode* prev = nullptr;
while (node) {
auto next = node->next;
node->next = prev;
prev = node;
node = next;
}
return prev;
}
public:
void reorderList(ListNode* head) {
auto fast = head;
auto slow = head;
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
auto mid = reverse(slow);
while (mid && mid->next) {
auto nextHead = head->next;
auto nextMid = mid->next;
head->next = mid;
mid->next = nextHead;
head = nextHead;
mid = nextMid;
}
}
};