zoukankan      html  css  js  c++  java
  • leetcode4:sort-list

    题目描述

    在O(n log n)的时间内使用常数级空间复杂度对链表进行排序。
    Sort a linked list in O(n log n) time using constant space complexity.
    示例1

    输入

    复制
    {3,2,4}

    输出

    复制
    {2,3,4}
    

    class Solution {
    public:
        ListNode* findMiddle(ListNode* head){
            ListNode* chaser = head;
            ListNode* runner = head->next;
            while(runner != NULL && runner->next != NULL){
                chaser = chaser->next;
                runner = runner->next->next;
            }
            return chaser;
        }
         
     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            if(l1 == NULL){
                return l2;
            }
            if(l2 == NULL){
                return l1;
            }
            ListNode* dummy = new ListNode(0);
            ListNode* head = dummy;
            while(l1 != NULL && l2 != NULL){
                if(l1->val > l2->val){
                    head->next = l2;
                    l2 = l2->next;
                }
                else{
                    head->next = l1;
                    l1 = l1->next;
                }
                head = head->next;
            }
            if(l1 == NULL){
                head ->next = l2;
            }
            if(l2 == NULL){
                head->next = l1;
            }
            return dummy->next;
        }
         
        ListNode* sortList(ListNode* head) {
            if(head == NULL || head ->next == NULL){
                return head;
            }
            ListNode* middle = findMiddle(head);
            ListNode* right = sortList(middle->next);
            middle -> next = NULL;
            ListNode* left = sortList(head);
            return mergeTwoLists(left, right);
        }
    };
  • 相关阅读:
    spring aop
    Linux进程管理命令
    逻辑卷管理-LVM(Logical Volume Manager)
    Linux磁盘与文件系统管理(二)
    Linux磁盘与文件系统管理(一)
    Linux后台运行和关闭、查看后台任务
    Linux用户管理及用户信息查询
    文件备份与压缩
    Liunx信息显示与文件搜索
    文本处理三剑客之 awk
  • 原文地址:https://www.cnblogs.com/hrnn/p/13417184.html
Copyright © 2011-2022 走看看