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:
/*algorithm : insert sort
*/
ListNode* insertionSortList(ListNode* head) {
ListNode* nh = NULL,*p = head,*next;
while(p){
next = p->next;
//search insert pos in sorted list
ListNode* q = nh,*prev=NULL;
while(q && q->val <= p->val){
prev = q;
q = q->next;
}
if(!prev){
p->next = q;
nh = p;
}else{
prev->next = p;
p->next = q;
}
p = next;
}
return nh;
}
};