• 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);
        }
    };
  • 相关阅读:
    DAY12 基本余数 运算符2
    DAY11 基本运算符
    DAY10 变量 常量 作用域
    DAY09 JAVA 类型转换
    DAY08 数据类型2
    DAY07 数据类型
    DAY06 JAVA基础语法1注释2标识符
    Beta冲刺集合
    Alpha冲刺集合
    高级软件工程实践总结
  • 原文地址:https://www.cnblogs.com/hrnn/p/13417184.html
Copyright © 2020-2023  润新知