Try โ€‚โ€‰HackMD

143. Reorder List


My Solution

The Key Idea for Solving This Coding Question

ๅฆ‚ไฝ•ไปฅไบคๅ‰็ทจ็น”็š„ๆ–นๅผๅˆไฝตๅ…ฉๅ€‹ๅ–ฎๅ‘้ˆ็ตไธฒๅˆ— (็ฌฌ 38 ~ 53 ่กŒ)

  1. ๅ‡่จญ head ๆŒ‡ๅ‘็š„ๅ–ฎๅ‘้ˆ็ตไธฒๅˆ—้•ทๅบฆๅฐๆ–ผๆˆ–็ญ‰ๆ–ผ head2 ๆŒ‡ๅ‘็š„ๅ–ฎๅ‘้ˆ็ตไธฒๅˆ—ใ€‚
  2. ๅ› ็‚บ it1->next ่ˆ‡ it2->next ็š†ๅฟ…้ ˆๆ”น่ฎŠๆ‰€่ฆๆŒ‡ๅ‘็š„็ฏ€้ปž๏ผŒๆ‰€ไปฅๅ…ˆๅˆ†ๅˆฅไปฅ tmp1 ่ˆ‡ tmp2 ็ด€้Œ„ it1->next ่ˆ‡ it2->next ็›ฎๅ‰ๆ‰€ๆŒ‡ๅ‘็š„็ฏ€้ปžใ€‚
  3. ไพ้กŒๆ„ๅฐ‡ it1->next ่ˆ‡ it2->next ๆŒ‡ๅ‘ๆ‡‰ๆŒ‡ๅ‘็š„็ฏ€้ปžใ€‚
    • it1->next ๆŒ‡ๅ‘ it2ใ€‚
    • it1 ่ตฐๅˆฐ tmp1 ๆ‰€ๅœจ็ฏ€้ปž (ไนŸๅฐฑๆ˜ฏ it1->next ๅŽŸๆœฌๆŒ‡ๅ‘็š„็ฏ€้ปž)ใ€‚
    • ๅ› ็‚บ head ๆŒ‡ๅ‘็š„ๅ–ฎๅ‘้ˆ็ตไธฒๅˆ—้•ทๅบฆๅฐๆ–ผๆˆ–็ญ‰ๆ–ผ head2 ๆŒ‡ๅ‘็š„ๅ–ฎๅ‘้ˆ็ตไธฒๅˆ—๏ผŒๆ‰€ไปฅ่ฆๅ…ˆๆชขๆŸฅ it1 ๆ˜ฏๅฆ็‚บ nullptr ใ€‚่‹ฅ it1 ็‚บ nullptr ๏ผŒ่กจ็คบๅˆไฝต็ตๆŸ๏ผŒ้›ข้–‹ while ่ฟดๅœˆใ€‚ๅฆๅ‰‡๏ผŒ็นผ็บŒๅˆไฝตใ€‚
    • it2->next ๆŒ‡ๅ‘ it1 ใ€‚
    • it2 ่ตฐๅˆฐ tmp2 ๆ‰€ๅœจ็ฏ€้ปž (ไนŸๅฐฑๆ˜ฏ it2->next ๅŽŸๆœฌๆŒ‡ๅ‘็š„็ฏ€้ปž)ใ€‚
  4. ้‡่ค‡ๆญฅ้ฉŸ 2 ่ˆ‡ 3 ใ€‚

C++ Code

/** * 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 { public: void reorderList(ListNode *head) { if (head == nullptr || head->next == nullptr) { return; } ListNode *preSlow = nullptr, *slow = head, *fast = head; while (fast != nullptr && fast->next != nullptr) { preSlow = slow; slow = slow->next; fast = fast->next->next; } // Break the list. preSlow->next = nullptr; // Reverse the second half of the list. ListNode *head2 = nullptr; while (slow != nullptr) { ListNode *tmp = slow->next; slow->next = head2; head2 = slow; slow = tmp; } // Interweave the two lists. ListNode *it1 = head, *it2 = head2; while (true) { ListNode *tmp1 = it1->next; ListNode *tmp2 = it2->next; it1->next = it2; it1 = tmp1; if (it1 == nullptr) { // Because the list length of it1 is shorter // than or equal to that of it2, it1 reaches // the end of its list first. break; } it2->next = it1; it2 = tmp2; } } };

Time Complexity

O(n)
n
is the total number of nodes in the linked list.

Space Complexity

O(1)

Miscellaneous