/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* insertionSortList(struct ListNode* head) {
if(head == NULL) return head;
struct ListNode *dummy= (struct ListNode *)malloc(sizeof(struct ListNode));
dummy->next=NULL; //new start of the sorted list
struct ListNode *pre=dummy; //insert node between pre and pre.next
struct ListNode *cur=head; //the node will be inserted
struct ListNode *Next=NULL; //the next node will be inserted
while(cur != NULL)
{
Next=cur->next;
//find the right place to insert
while(pre->next != NULL && pre->next->val < cur->val)
{
pre=pre->next;
}
//insert between pre and pre.next
cur->next=pre->next;
pre->next=cur;
pre=dummy;
cur=Next;
}
return dummy->next;
}