您的位置:首页 > 其它

[leetcode] Insertion Sort List

2015-07-20 15:47 399 查看
#include<iostream>
using namespace std;

struct ListNode
{
int value;
ListNode* next;
ListNode(int value):value(value),next(NULL){};
};
ListNode* Insertsort(ListNode* head)
{
if(!head)
return NULL;
ListNode* dump=new ListNode(INT_MIN);
dump->next=head;
bool flag=false;
for(ListNode* pre=dump;pre->next!=NULL;)
{
ListNode* p=NULL;
for(ListNode* cur=dump;cur!=pre->next;p=cur,cur=cur->next)
{
if(pre->next->value>cur->value)
{
continue;
}
p->next=pre->next;
pre->next=pre->next->next;
p->next->next=cur;
flag=true;
break;
}
if(!flag)
pre=pre->next;
else
flag=false;
}

return dump->next;
}

void main()
{
int a[10]={2,5,1,5,3,2,4,9,8,1};
ListNode* head=new ListNode(a[0]);
ListNode* cur=head;
for(int i=1;i<10;i++)
{
ListNode* node=new ListNode(a[i]);
cur->next=node;
cur=cur->next;
}
head=Insertsort(head);
while(head)
{
cout<<head->value<<' ';
head=head->next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: