leetcode 148 sortlist

来源:互联网 发布:名校毕业生知乎 编辑:程序博客网 时间:2024/06/04 18:31

原题:

Sort a linked list in O(n log n) time using constant space complexity.


Seen this question in a real interview before?   
Yes
 

然而我把快排写完了才发现超时了。。。

真是悲剧。。。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; *///快速排序struct ListNode* sortList(struct ListNode* head) {    int length=0;    struct ListNode* p;    p=head;    while(p!=NULL)    {        length++;        p=p->next;    }    //printf("%d",length);    struct ListNode* sort(struct ListNode* head,int length);    return sort(head,length);}struct ListNode* sort(struct ListNode* head,int length){    if(length<2)        return head;    int left=0;    int temp=head->val;    //printf("temp:%d",temp);    struct ListNode* p,*flag;    flag=head;    p=head;    int orilength=length;    while(length>1)    {        if(p->next->val<temp)        {            struct ListNode* pCon;            pCon=p->next;            p->next=p->next->next;            left++;            pCon->next=head;            head=pCon;        }        else        {            p=p->next;        }        length--;    }    //printf("left:%d",left);    head=sort(head,left);    flag->next=sort(flag->next,orilength-left-1);    //printf("head->val:%d",head->val);    return head;}

看了分析,说是应该用归并排序。。。

那我等有空了再补一发吧。

原创粉丝点击