zoukankan      html  css  js  c++  java
  • 148. Sort List

    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;
        }
  • 相关阅读:
    (0)git安装
    [SCOI2008]奖励关
    bzoj1007 [HNOI2008]水平可见直线
    【bzoj1060】[ZJOI2007]时态同步
    【bzoj2705】[SDOI2012]Longge的问题
    【bzoj3505】[Cqoi2014]数三角形
    【bzoj3747】[POI2015]Kinoman
    P1072 Hankson的趣味题
    poj1845 数论 快速幂
    【bzoj1965】[Ahoi2005]SHUFFLE 洗牌
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5607307.html
Copyright © 2011-2022 走看看