• 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;
        }
    };
  • 相关阅读:
    Best code水题之路
    我的CodeF水A题之路
    studing(来自转载)
    BFS
    fibonacci数列(五种)
    Redis阻塞队列原理学习
    the enum hack
    Divide Two Integers
    Surrounded Regions
    Search in Rotated Sorted Array
  • 原文地址:https://www.cnblogs.com/vercont/p/10210250.html
Copyright © 2020-2023  润新知