您的位置:首页 > 其它

insertion-sort-list

2017-03-22 11:18 351 查看
题目描述

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;

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