• LeetCode OJ-- Sort List **@


    链表排序,要求使用 O(nlgn) 时间,常量空间。

    使用归并的思路

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *findMid(ListNode *head)
        {
            ListNode *mid;
            ListNode *fast = head->next;
            ListNode *slow = head;
            while(fast && fast->next)
            {
                fast = fast->next;
                fast = fast->next;
                slow = slow->next;
            }
            mid = slow;
            return mid;
        }
        ListNode *sortList(ListNode *head) {
            if(head == NULL || head->next == NULL)
                return head;
            ListNode *tmp = findMid(head);
            ListNode *right = sortList(tmp->next);
            tmp->next = NULL;
            ListNode *left = sortList(head);
            
            ListNode *newHead = new ListNode(-1);
            newHead->next = merge(left,right);
            return newHead->next;
        }
        ListNode *merge(ListNode *left, ListNode *right)
        {
            ListNode *dummy = new ListNode(-1);
            for(ListNode *p = dummy; left!=NULL || right!= NULL; p = p->next)
            {
                int leftVal = left == NULL? INT_MAX:left->val;
                int rightVal = right == NULL?INT_MAX:right->val;
                if(leftVal <= rightVal)
                {
                    p->next = left;
                    left = left->next;
                }
                else
                {
                    p->next = right;
                    right = right->next;
                }
            }
            return dummy->next;
        }
    };
  • 相关阅读:
    模拟黑客入侵,恶搞小伙伴的利器
    牛客网算法竞赛难题
    ybt ——1346【例4-7】亲戚
    FBI树
    noi2020第二题
    noi2020第一题
    Happiness
    YiJuWuLiaoDeHua
    挂掉了一个u盘
    NOIp2020
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3916405.html
Copyright © 2020-2023  润新知