zoukankan      html  css  js  c++  java
  • Sort List

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

    思路:使用O(nlogn)时间复杂度和常数空间复杂度,我们想到可以用归并排序。

    1)找到链表中间位置

    2)将两个链表按序合并链表

    3)对所给链表进行整体的归并排序

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *getMiddle(ListNode *head)
        {
            ListNode *slow=head;
            ListNode *fast=head;
            while(fast->next!=NULL&&fast->next->next!=NULL)
            {
                slow=slow->next;
                fast=fast->next->next;
            }
            return slow;
        }
        ListNode *Merge(ListNode *head1,ListNode *head2)
        {
            ListNode *dummy=new ListNode(-1);
            ListNode *cur=dummy;
            while(head1!=NULL&&head2!=NULL)
            {
                if(head1->val<head2->val)
                {
                    cur->next=head1;
                    head1=head1->next;
                }
                else
                {
                    cur->next=head2;
                    head2=head2->next;
                }
                cur=cur->next;
            }
            while(head1!=NULL)
            {
                cur->next=head1;
                head1=head1->next;
                cur=cur->next;
            }
            while(head2!=NULL)
            {
                cur->next=head2;
                head2=head2->next;
                cur=cur->next;
            }
            return dummy->next;
        }
        ListNode *sortList(ListNode *head) {
            if(head==NULL||head->next==NULL)
                return head;
            ListNode *mid=getMiddle(head);
            ListNode *pHead2=mid->next;
            mid->next=NULL;
            return Merge(sortList(head),sortList(pHead2));
        }
    };
  • 相关阅读:
    APIO2019游记
    ZJOI2019赛季回顾
    「HNOI 2019」白兔之舞
    LOJ #6539 奇妙数论题
    BZOJ4314 倍数?倍数!
    伯努利数学习笔记&&Luogu P3711 仓鼠的数学题
    BZOJ 5093[Lydsy1711月赛]图的价值 线性做法
    AtCoder Grand Contest 030题解
    Codeforces Round #542 (Div. 1) 题解
    Codeforces Round #541 (Div. 2)题解
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3807572.html
Copyright © 2011-2022 走看看