對單鏈表進行插入排序,返回排序後頭節點。要求穩定排序。
dummy 虛擬頭節點,值為 INT_MINcur 遍歷原鏈表cur,在已排序部分鏈表中找到插入位置 pos(最後一個 ≤ cur->val 的節點)cur 插入 pos 之後class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode dummy(INT_MIN);
ListNode* cur = head;
while (cur) {
ListNode* pos = findInsertPos(&dummy, cur->val);
ListNode* tmp = cur->next; // 保存下一個待處理節點
cur->next = pos->next;
pos->next = cur;
cur = tmp;
}
return dummy.next;
}
private:
ListNode* findInsertPos(ListNode* head, int x) {
ListNode* pre = nullptr;
ListNode* cur = head;
while (cur && cur->val <= x) {
pre = cur;
cur = cur->next;
}
return pre; // 插在 pre 之後
}
};
cur->next,必須先保存若要求 O(n log n),需用歸並排序(LeetCode 148),見下文。