zoukankan      html  css  js  c++  java
  • 148. Sort List

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

    链表的归并排序。

    /**
     * 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 == NULL || head->next == NULL) return head;
            
            ListNode *tail = head, *mid = head, *pre = head;
            
            while (tail && tail->next) {
                pre = mid;
                mid = mid->next;
                tail = tail->next->next;
            }
            //change pre next to null, make two sub list(head to pre, p1 to p2)
            pre->next = NULL;
            
            ListNode *h1 = sortList(head);
            ListNode *h2 = sortList(mid);
            
            return merge(h1, h2);
        }
        ListNode* merge(ListNode *h1, ListNode *h2) {
            if (h1 == NULL) return h2;
            if (h2 == NULL) return h1;
            
            if (h1->val < h2->val) {
                h1->next = merge(h1->next, h2);
                return h1;
            } else {
                h2->next = merge(h1, h2->next);
                return h2;
            }
        }
    };
  • 相关阅读:
    每日日报30
    每日作业报告
    每日作业报告
    每日作业报告
    每日作业报告
    每日作业报告
    每日作业报告
    每日作业报告
    每日作业报告
    Java学习的第四十三天
  • 原文地址:https://www.cnblogs.com/linjj/p/5256450.html
Copyright © 2011-2022 走看看