[leetcode] Insertion Sort List

来源:互联网 发布:精致的利己主义 知乎 编辑:程序博客网 时间:2024/05/20 05:59
#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;    }}
0 0
原创粉丝点击