Reorder List 解題教學:3 種解法完整比較|LeetCode 143 Best Practice

Reorder List 解題教學示意圖|LeetCode 143

本文完整拆解 LeetCode 143 Reorder List 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Reorder List 一次弄懂。

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link


You are given the head of a singly linked-list. The list can be represented as:

L0 → L1 → … → Ln - 1 → Ln

Reorder the list to be on the following form:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …

You may not modify the values in the list’s nodes. Only nodes themselves may be changed.

 

Example 1:

Input: head = [1,2,3,4]
Output: [1,4,2,3]

Example 2:

Input: head = [1,2,3,4,5]
Output: [1,5,2,4,3]

 

Constraints:

  • The number of nodes in the list is in the range [1, 5 * 104].
  • 1 <= Node.val <= 1000

Python

				
					# time complexity: O(n)
# space complexity: O(1)
from typing import Optional


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        if not head:
            return
        fast = head
        slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next

        prev = None
        curr = slow
        while curr:
            curr.next, prev, curr = prev, curr, curr.next

        first = head
        second = prev
        while second.next:
            first.next, first = second, first.next
            second.next, second = first, second.next

        return


root = ListNode(1)
root.next = ListNode(2)
root.next.next = ListNode(3)
root.next.next.next = ListNode(4)
root.next.next.next.next = ListNode(5)
root.next.next.next.next.next = ListNode(6)
print(Solution().reorderList(root))
				
			

Reorder List 解題思路

把 L0→L1→…→Ln 重排成 L0→Ln→L1→Ln-1→…,可以拆成三個獨立的經典子問題:用快慢指針找到中點、把後半段反轉、再把前後兩段交錯合併。每一步都是 O(n) 且原地完成,組合起來就能滿足不使用額外空間的要求。

Reorder List 演算法步驟

  1. 用快慢指針找到串列中點,slow 停在中間節點。
  2. 從中點之後切斷,把後半段就地反轉。
  3. 用兩個指標分別指向前半段與反轉後的後半段頭部。
  4. 交替接上兩段的節點,直到後半段用完。

Reorder List 複雜度分析

項目複雜度
時間複雜度O(n)
空間複雜度O(1)

找中點、反轉、合併各需一趟線性掃描,時間為 O(n)。全程只用指標變數原地操作,空間 O(1)——這是本解法的價值所在。

Reorder List 的邊界情況與常見錯誤

  • 節點數為奇數時,中間節點應留在前半段。
  • 切斷中點與後半段的連結很重要,忘了會形成環。
  • 長度 0、1、2 的串列要能正確處理(通常不需重排)。
  • 合併時要小心保存 next 指標再改接,否則會遺失節點。

Reorder List 其他解法比較

解法時間空間說明
把節點全放進陣列再依索引重接O(n)O(n)最好寫但違反 O(1) 空間
用雙向佇列前後交替取O(n)O(n)思路直觀,空間同樣較差
找中點 + 反轉 + 合併O(n)O(1)本文採用