LeetCode-148. Sort List

1. 题目

Sort List

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

2. 分析

题目限定时间复杂度必须为O(nlogn)
只能用快速排序、归并排序、堆排序
根据单链表的特点,最适于用归并排序
可复用 Merge Two Sorted Lists 中的代码

3. 代码

class Solution {
public:
    ListNode* sortList(ListNode* head) {
        // 注意第一步应该 return head; 不要误写成 return NULL;
        if(head == NULL || head->next == NULL)
            return head;

        // 不要写成  ListNode *prev = NULL;
        ListNode *prev = head;
        ListNode *slow = head;
        ListNode *fast = head;

        while(fast != NULL && fast->next != NULL)
        {
            prev = slow;
            slow = slow->next;
            fast = fast->next->next;
        }

        prev->next = NULL;

        // 写成  return mergeTwoLists(head, slow);   是错误的
        return mergeTwoLists(sortList(head), sortList(slow));
    }

    ListNode* mergeTwoLists(ListNode *l1, ListNode *l2) {
        // 复用mergeTwoLists
    }

};

完整源代码放于github

猜你喜欢

转载自blog.csdn.net/tao_ba/article/details/80712401