• Leetcode 148. Sort List


    148. Sort List

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

    Example 1:

    Input: 4->2->1->3
    Output: 1->2->3->4
    

    Example 2:

    Input: -1->5->3->4->0
    Output: -1->0->3->4->5

    提解:归并排序,递归思想,然后就是获得链表中间位置方法的思路:设置slow,fast两个指针。设置快慢指针的思路会经常在链表题里面出现(反转链表...),要熟练使用。
    #include <iostream>
    using namespace std;
    
    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;
            //get middle node
            //not right if write: *fast = head. Otherwise, {2, 1} will not be sorted.
            ListNode *slow = head, *fast = head->next;
            while (fast && fast->next)
            {
                slow = slow->next;
                fast = fast->next->next;
            }
            ListNode *left = head, *right = slow->next;
            slow->next = NULL;
            left = sortList(left);
            right = sortList(right);
            return Merge(left, right);
        }
    
        ListNode *Merge(ListNode *Left, ListNode *Right) {
    
            if (!Left) return Right;
            if (!Right) return Left;
            ListNode *h = NULL;
            if (Left->val < Right->val) {
                h = Left;
                h->next = Merge(Left->next, Right);
            }
            else {
                h = Right;
                h->next = Merge(Left, Right->next);
            }
    
            return h;
        }
    };
    
    void test_data()
    {
        ListNode *head = new ListNode(0);
        ListNode *p ;
        p = head;
        Solution s;
        int n = 0;
        int T = 5;
        //-1 5 3 4 0
        while (T-- && cin >> n)
        {
            ListNode *q;
            q = new ListNode(n);
            p->next = q;
            p = q;
        }
    
        head = head->next;
        s.sortList(head);
    
        while (head)
        {
            cout << head->val << " ";
            head = head->next;
        }
    }
    
    int main()
    {
    
        test_data();
    
        return 0;
    
    }

  • 相关阅读:
    Java自定义异常
    Java异常处理教程
    Java异常抛出
    Java泛型方法和构造函数
    Java泛型类
    Java继承方法隐藏(覆盖)
    Java继承和构造函数
    Java方法覆盖教程
    PHP设置时区
    PHPCMS v9的表单向导实现问答咨询功能的方法
  • 原文地址:https://www.cnblogs.com/douzujun/p/10628871.html
Copyright © 2020-2023  润新知