【leetcode】148. 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;
}

猜你喜欢

转载自www.cnblogs.com/JesseTsou/p/9589408.html