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;
        }
    };
  • 相关阅读:
    认识v$fixed_view_definition
    V$、GV$、X$、V_$、GV_$之间的关系
    ORACLE OEM
    ORACLE表空间
    linux
    系统数据库备份恢复
    linux -- #!/bin/bash
    linux -- ubuntu 脚本开机自启动
    linux -- chown修改文件拥有者和所在组
    php -- php控制linux关机、重启、注销
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3916405.html
Copyright © 2011-2022 走看看