單向鏈表的歸併排序,難點不在合併,而在遞迴時如何把鏈表切成兩半。
技巧是用兩個指標 p 與 f 同時出發:p 每次走一步,f 每次走兩步。等 f 走到尾端,p 剛好落在中點。這類「快慢指標」的思路,跟那道經典的燒繩計時邏輯題頗有異曲同工之妙。
程式碼如下:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode p = head;
ListNode f = head.next;
while (f.next != null && f.next.next != null) { // 讓 p 停在正中點
p = p.next;
f = f.next.next;
}
ListNode h2 = sortList(p.next);
p.next = null; // 從中點斷開
return merge(sortList(head), h2);
}
public ListNode merge(ListNode h1, ListNode h2) {
ListNode hn = new ListNode(-1); // 哨兵節點,省去頭部長度判斷
ListNode c = hn;
while (h1 != null && h2 != null) {
if (h1.val <= h2.val) {
c.next = h1;
h1 = h1.next;
} else {
c.next = h2;
h2 = h2.next;
}
c = c.next;
}
if (h1 == null) {
c.next = h2;
} else {
c.next = h1;
}
return hn.next;
}
}
兩個值得留意的細節:一是切開鏈表時必須把 p.next 設為 null,否則遞迴會無限打轉;二是合併時用一個值為 −1 的哨兵節點當起點,最後回傳 hn.next,可以省掉一堆「第一個元素誰來當」的判斷。