【Leedcode】Insertion Sort List

时间:2023-03-09 07:20:19
【Leedcode】Insertion Sort List

Sort a linked list using insertion sort.

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
ListNode dummy(INT_MIN);
ListNode *cur = head;
while (cur != nullptr) {
ListNode *pos = findInsertPos(&dummy, cur->val);
ListNode *temp = cur->next;
cur->next = pos->next;
pos->next = cur;
cur = temp;
}
return dummy.next;
}
private:
ListNode *findInsertPos(ListNode *before_head, int key) {
ListNode *pre = nullptr, *cur = before_head;
while (cur != nullptr && cur->val <= key) {
pre = cur;
cur = cur->next;
}
return pre;
}
};