题目描述
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:
ListNode *insertionSortList(ListNode *head) {
if(head==NULL|| head->next==NULL)
return head;
ListNode* prehead=new ListNode(INT_MIN);
prehead->next=head;
ListNode* phead=prehead;
ListNode* cur=head;
ListNode* next=head->next;
while(next!=NULL)
{
if(next->val>=cur->val)
{
cur=cur->next;
next=next->next;
}
else
{
ListNode* temp=next;
next=temp->next;
cur->next=next;
while(phead->next!=cur)
{
if(temp->val>phead->next->val)
phead=phead->next;
else
break;
}
temp->next=phead->next;
phead->next=temp;
phead=prehead;
}
}
return prehead->next;
}
};