题目
用插入排序对链表排序
样例
Given 1->3->2->0->null
, return 0->1->2->3->null
C++代码
ListNode *insertionSortList(ListNode *head) {
// write your code here
if (!head) return NULL;
ListNode* root = head;
head = head->next;
root->next = NULL;
ListNode* p;
while (head)
{
p = head;
head = head->next;
p->next = NULL;
ListNode* t, *ft;
ft = t = root;
if (root->val >= p->val)
{
p->next = root;
root = p;
}
else
{
while (t && t->val < p->val)
{
ft = t;
t = t->next;
}
if (!t) ft->next = p;
else
{
ft->next = p;
p->next = t;
}
}
}
return root;
}