解決大部分鏈表重排、回文、合併問題的利器:
// 快慢指針找中點(前半段較長)
ListNode *slow = head, *fast = head;
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
// 就地反轉(三指針法)
ListNode* reverse(ListNode* head) {
if (!head || !head->next) return head;
ListNode *pre = nullptr, *cur = head, *nxt;
while (cur) {
nxt = cur->next;
cur->next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
題目:`L0→L1→…→Ln-1→Ln` 重排為 `L0→Ln→L1→Ln-1→…`
ListNode *p1 = head, *p2 = reversed_head;
while (p2) {
ListNode *tmp = p2->next;
p2->next = p1->next;
p1->next = p2;
p1 = p1->next->next; // 跳過剛插入的節點
p2 = tmp;
}
鏈表題核心在於指針操作的嚴謹性,掌握「找中點 + 反轉 + 合併」三板斧,配合邊界處理,可破解 80% 以上鏈表問題。