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));
        }
    };
  • 相关阅读:
    JAVA学习前应该了解
    JAVA帝国的诞生
    常用的快捷方式
    MarkDown学习
    运动检测
    图像分割
    感知机
    线性判别函数
    距离
    概率密度估计笔记——非参数估计
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3807572.html
Copyright © 2011-2022 走看看