leetcode148. Sort List

Posted JESSET

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode148. Sort List相关的知识,希望对你有一定的参考价值。

题目说明

https://leetcode-cn.com/problems/sort-list/description/
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

解法1

使用归并排序对链表进行排序

/*
 * 时间复杂度:O(nlogn)
 * 归并排序的递归实现
 */
ListNode* sortList(ListNode* head) {
    if (head == NULL || head->next == NULL)
        return head;
    ListNode *slow = head;
    ListNode *fast = head->next;

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

    ListNode *half = slow->next;
    slow->next = NULL;

    return merge(sortList(head),sortList(half));
}

ListNode *merge(ListNode* head1,ListNode* head2)
{
    ListNode *dummy = new ListNode(0);
    ListNode *l3 = dummy;

    ListNode *l1 = head1;
    ListNode *l2 = head2;

    while(l1 && l2 ){
        if (l1->val < l2->val){
            l3->next = l1;
            l1 = l1->next;
        } else if (l1->val >= l2->val){
            l3->next = l2;
            l2 = l2->next;
        }
        l3 = l3->next;
    }
    ListNode *last = (l1 == NULL)?l2:l1;
    l3->next = last;

    ListNode *ret = dummy->next;
    delete dummy;
    return ret;
}

以上是关于leetcode148. Sort List的主要内容,如果未能解决你的问题,请参考以下文章

[Lintcode]98. Sort List/[Leetcode]148. Sort List

#Leetcode# 148. Sort List

leetcode148. Sort List

Leetcode148-Sort_List

leetcode148. Sort List

LeetCode-148-Sort List