sort-list

来源:互联网 发布:apache 允许目录列表 编辑:程序博客网 时间:2024/05/23 23:10

题目描述

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

使用归并排序,严格来说空间复杂度并不是常量,因为用到了栈,但是好像大多数人都是利用归并排序的,姑且这么写吧。比较简单。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *sortList(ListNode *head) {        if(head==NULL||head->next==NULL)            return head;        return recursort(head);    }    ListNode *recursort(ListNode *head)    {        if(head==NULL ||head->next==NULL)            return head;        ListNode* fast=head;        ListNode*  slow=head;        while(fast!=NULL&&fast->next!=NULL&&fast->next->next!=NULL)            {            fast=fast->next->next;            slow=slow->next;        }        ListNode* left=head;        ListNode* right=slow->next;        slow->next=NULL;        ListNode* ln=recursort(left);        ListNode* rn=recursort(right);        ListNode* res=new ListNode(0); //借用临时变量        ListNode* tres=res;        while(ln!=NULL&&rn!=NULL)            {            if(ln->val<rn->val){                tres->next=ln;                tres=tres->next;                ln=ln->next;            }            else{                tres->next=rn;                tres=tres->next;                rn=rn->next;            }        }        if(!ln)             tres->next=rn;        else            tres->next=ln;        ListNode* temp=res->next;        delete res;   //注意释放空间        res=NULL;        return temp;    }};
0 0
原创粉丝点击