积少成多

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

==============

题目:有时间和空间复杂度限制

单链表适合利用归并排序,

双向链表适合利用快速排序,

复用mergeTwoList()代码

1,利用fast/slow方法找到链表的中间节点mid,将链表分为head1和head2两个部分

2,递归处理

3,分别merge两个链表

====

code如下:

///
    ListNode *mergeList(ListNode *l1, ListNode *l2){
        if(l1==nullptr) return l2;
        if(l2==nullptr) return l1;
        ListNode dummy(-1);
        ListNode *p = &dummy;
        while(l1 || l2){
            int val1 = l1==nullptr? INT_MAX : l1->val;
            int val2 = l2==nullptr? INT_MAX : l2->val;
            if(val1<=val2){
                p->next = l1;
                l1 = l1->next;
            }else{
                p->next = l2;
                l2 = l2->next;
            }
            p = p->next;
        }
        cout<<"---";showList(dummy.next);

        return dummy.next;
    }
    ListNode *sortList(ListNode *head){
        if(head==nullptr || head->next==nullptr) return head;
        ListNode *fast,*slow;
        fast = slow = head;
        while(fast->next && fast->next->next){
            slow = slow->next;
            fast = fast->next->next;
        }
        fast = slow;
        slow = slow->next;
        fast->next = nullptr;

        //showList(head);
        //showList(slow);cout<<endl;
        ListNode *l1 = sortList(head);
        ListNode *l2 = sortList(slow);
        head = mergeList(l1,l2);

        return head;
    }

 

posted on 2016-06-22 15:35  x7b5g  阅读(159)  评论(0编辑  收藏  举报