• sort-list leetcode C++


    Sort a linked list in O(n log n) time using constant space complexity.

    C++

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* sortList(ListNode* head){
            if (!head||!head->next) return head;
            ListNode* slow = head;
            ListNode* fast = head;
            ListNode* pre = head;
            while (fast && fast->next){
                pre = slow;
                slow = slow->next;
                fast = fast->next->next;
            }
            pre->next = NULL;
            return merge(sortList(head),sortList(slow));
        }
        ListNode* merge(ListNode* left,ListNode* right){
           ListNode *head;
           if (left->val < right->val){
                    head = left;
                    left = left->next;
           }else{
                    head = right;
                    right = right->next;
            }
            ListNode *cur = head;
            while(left && right){
                if (left->val < right->val){
                    cur->next = left;
                    left = left->next;
                }else{
                    cur->next = right;
                    right = right->next;
                }
                cur = cur->next;
            }
            if (left) cur->next = left;
            if (right) cur->next = right;
            return head;
        }
        ListNode* merge2(ListNode*left, ListNode* right){
            ListNode* head = new ListNode(-1);
            ListNode* cur = head;
            while(left && right){
                if (left->val < right->val){
                    cur->next = left;
                    left = left->next;
                }else{
                    cur->next = right;
                    right = right->next;
                }
                cur = cur->next;
            }
            if (left) cur->next = left;
            if (right) cur->next = right;
            return head->next;
        }
    };
  • 相关阅读:
    「训练反思18」 (8.16) 认清自己
    「训练日志17」 (8.12) 崩盘
    「训练日志16」 8.11 下坠
    「训练日志15」 (8.10)
    「训练反思15」(8.10)
    「训练日志14 」(8.9) 失败
    训练日志13 (8.7)
    Linux 设置vim指令
    训练日志12 (8.5)
    训练反思12 (8.5)
  • 原文地址:https://www.cnblogs.com/vercont/p/10210250.html
Copyright © 2020-2023  润新知