/**************************************************************************
*
* 147. [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)
*
* Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.
*
**************************************************************************/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode NODE;
NODE *findInsertPos(NODE *dummy, int val) {
NODE *pre = NULL;
while (dummy && dummy->val <= val) {
pre = dummy;
dummy = dummy->next;
}
return pre;
}
NODE *insertionSortList(NODE *head){
if (NULL == head || NULL == head->next) return head;
NODE dummy;
dummy.val = INT_MIN;
dummy.next = NULL;
while (head) {
NODE *pos = findInsertPos(&dummy, head->val);
// 下一个节点tmp已经挂上,只需关心插入即可
NODE *tmp = head->next;
head->next = pos->next;
pos->next = head;
head = tmp;
}
return dummy.next;
}