147. Insertion Sort List

来源:互联网 发布:网络剧大全 编辑:程序博客网 时间:2024/04/20 02:56
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */ //80 msclass Solution {public:    ListNode* insertion(ListNode* temp,ListNode* head)     {        if(temp->val<head->val)        {            temp->next=head;            return temp;        }        ListNode* a=head;        while(a->next&&a->next->val<temp->val) a=a->next;        if(!a->next)         {            temp->next=NULL;            a->next=temp;        }        else        {            temp->next=a->next;            a->next=temp;        }        return head;    }    ListNode* insertionSortList(ListNode* head) {        if(!head) return head;        ListNode* temp1=head->next;        ListNode* head0=head;        head0->next=NULL;        while(temp1)        {            ListNode* temp=temp1->next;            head0=insertion(temp1,head0);            temp1=temp;        }        return head0;    }};
//80msclass Solution {public:    ListNode* insertionSortList(ListNode* head) {        if(!head) return head;        ListNode myhead(INT_MIN),*cur,*temp;        while(head)        {            for(cur=&myhead;cur->next&&cur->next->val<head->val;) cur=cur->next;            temp=head->next;            head->next=cur->next;            cur->next=head;                        head=temp;        }        return myhead.next;    }};
//24ms//即使是插入排序,也不需要每次都从头查找class Solution {public:    ListNode* insertionSortList(ListNode* head) {        if(!head) return head;        ListNode myhead(INT_MIN),*cur=&myhead,*temp;        while(head)        {            if(head->val<cur->val) cur=&myhead;            for(;cur->next&&cur->next->val<head->val;) cur=cur->next;            temp=head->next;            head->next=cur->next;            cur->next=head;                        head=temp;        }        return myhead.next;    }};
0 0
原创粉丝点击