Problem
Sort a linked list using insertion sort.
Code
ListNode *insertionSortList(ListNode *head) { if(!head)
return 0;
ListNode *node = head;
while(node->next){
if(node->next->val < head->val){
ListNode *tmp = node->next;
node->next = tmp->next;
tmp->next = head;
head = tmp;
}
else{
ListNode *pos = head;
while(pos != node && node->next->val > pos->next->val)
pos = pos->next;
if(pos == node)
node = node->next;
else{
ListNode *tmp = pos->next;
pos->next = node->next;
node->next = node->next->next;
pos->next->next = tmp;
}
}
}
return head;
}
No comments:
Post a Comment