147. Insertion Sort List
鏈表排序,插入排序
class Solution {
public:
ListNode * insertionSortList(ListNode* head) {
if (head == nullptr || head->next == nullptr)return head;
//創建一個系統最小節點
ListNode dummy(INT_MIN);
for (ListNode*cur = head; cur;) {
auto pos = findInsertPos(&dummy, cur->val);
//把cur節點插入pos節點之後
ListNode*tmp = cur->next;
cur->next = pos->next;
pos->next = cur;
cur = tmp;
}
return dummy.next;
}
ListNode*findInsertPos(ListNode*head, int x) {
ListNode*pre = nullptr;
for (ListNode*cur = head; cur&&cur->val <= x; pre = cur, cur = cur->next);
return pre;
}
};