Leetcode 148 Sort List

题目:Sort a linked list in O(nlogn)time using constant space complexity.

题解:本来想用快排来做,但是看了网上博客说,在快排的最坏情况下是O(n平方),所以就用了归并排序。


</pre><pre code_snippet_id="653676" snippet_file_name="blog_20150426_3_5518759" name="code" class="html">class Solution {
private:
    ListNode *getMid(ListNode *head){   //找到中间位置
        if(!head) return NULL;
        if(!(head->next)) return head;
        ListNode *slow,*fast;
        slow = head;
        fast = head->next;
        while(fast&&fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
    
    ListNode *MemeryArray(ListNode *l1,ListNode *l2)    //合并两个链表
    {
        if(!l1) return l2;
        if(!l2) return l1;
        ListNode *merge=new ListNode(0);
        ListNode *head = NULL;
        head = merge;
        while(l1&&l2){
            ListNode *node = new ListNode(0);
            if(l1->val >l2->val)
            {
                node->val = l2->val;
                l2 = l2->next;
            }else{
                node->val = l1->val;
                 l1 = l1->next;
                
            }
            merge->next = node;
            merge = merge->next;
        }
        if(l1){
            merge->next = l1;
            merge = merge->next;
        }
        if(l2){
            merge->next = l2;
            merge = merge->next;
        }
        head = head->next;
        return head;
    }
public:
    ListNode *sortList(ListNode *head) {
        if(!head) return NULL;
        if(!head->next) return head;
        ListNode *nextpart = new ListNode(0);
        ListNode *mid = getMid(head);
        if(mid)
        {
            nextpart = mid->next;
            mid->next = NULL;
        }
        return MemeryArray(sortList(head),sortList(nextpart));
    }
};



         
       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值