跳至主要内容

143. Reorder List

143. Reorder List

題意

給定一個 linked list

L0L_0L1L_1 → … →Ln1L_{n - 1}LnL_n 改為 L0L_0LnL_nL1L_1Ln1L_{n-1}L2L_2Ln2L_{n-2} → …

限制

  • 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;
}
}
};