您的位置:首页 > 其它

LeetCode:Insertion Sort List

2014-08-26 17:05 344 查看
Sort a linked list using insertion sort

ListNode *insertionSortList(ListNode *head)
{
if(!head || !head->next)
return head;

ListNode* result =head;
ListNode* p = head;
ListNode* pre =NULL;

head = head->next;
result->next = NULL;
while(head != NULL)
{
p = result;
while(p != NULL && head->val > p->val)
{
pre=p;
p=p->next;
}
if(p == result)
{
result = head;
head = head->next;
result -> next = p;
}
else
{
pre->next = head;
head = head->next;
pre->next->next = p;
}
}
return result;
}

已AC  276ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息