zoukankan      html  css  js  c++  java
  • LeetCode OJ-- Sort List **@

    链表排序,要求使用 O(nlgn) 时间,常量空间。

    使用归并的思路

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *findMid(ListNode *head)
        {
            ListNode *mid;
            ListNode *fast = head->next;
            ListNode *slow = head;
            while(fast && fast->next)
            {
                fast = fast->next;
                fast = fast->next;
                slow = slow->next;
            }
            mid = slow;
            return mid;
        }
        ListNode *sortList(ListNode *head) {
            if(head == NULL || head->next == NULL)
                return head;
            ListNode *tmp = findMid(head);
            ListNode *right = sortList(tmp->next);
            tmp->next = NULL;
            ListNode *left = sortList(head);
            
            ListNode *newHead = new ListNode(-1);
            newHead->next = merge(left,right);
            return newHead->next;
        }
        ListNode *merge(ListNode *left, ListNode *right)
        {
            ListNode *dummy = new ListNode(-1);
            for(ListNode *p = dummy; left!=NULL || right!= NULL; p = p->next)
            {
                int leftVal = left == NULL? INT_MAX:left->val;
                int rightVal = right == NULL?INT_MAX:right->val;
                if(leftVal <= rightVal)
                {
                    p->next = left;
                    left = left->next;
                }
                else
                {
                    p->next = right;
                    right = right->next;
                }
            }
            return dummy->next;
        }
    };
  • 相关阅读:
    数据库 第一、二、三范式
    JVM垃圾回收(GC)整理总结学习
    ConcurrentHashMap
    Java GC、新生代、老年代
    Android -- 查看手机中所有进程
    ThreadLocal
    Android -- DrawerLayout
    WeakReference与SoftReference
    ASP.NET Core Web服务器 Kestrel和Http.sys 特性详解
    微服务架构体系
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3916405.html
Copyright © 2011-2022 走看看