leetcode#148 排序链表

leetcode#148 排序链表

题目:

给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。

进阶:

  • 你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
示例:

图1

输入:head = [4,2,1,3]
输出:[1,2,3,4]

思路:

归并排序,因为链表的合并可以不占用空间,所以可以做到空间O(1)。
细节比较多。

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
public:
    ListNode *merge(ListNode *head1, ListNode *head2)
    {
        ListNode *dummy = new ListNode(0, NULL);
        ListNode *p = head1, *q = head2, *now = dummy;
        while (p && q)
        {
            if (p->val < q->val)
                now->next = p, p = p->next, now = now->next, now->next = NULL;
            else
                now->next = q, q = q->next, now = now->next, now->next = NULL;
        }
        while (p)
            now->next = p, p = p->next, now = now->next, now->next = NULL;
        while (q)
            now->next = q, q = q->next, now = now->next, now->next = NULL;
        return dummy->next;
    }
    ListNode *sortList(ListNode *head)
    {
        if (!head)
            return NULL;
        int len = 0;
        ListNode *tmp = head;
        while (tmp)
            ++len, tmp = tmp->next;
        ListNode *dummy = new ListNode(0, head);
        for (int sublen = 1; sublen < len; sublen <<= 1)
        {
            ListNode *pre = dummy, *cur = dummy->next;
            while (cur)
            {
                ListNode *head1 = cur;
                for (int i = 1; i < sublen && cur->next; ++i)
                    cur = cur->next;
                ListNode *head2 = cur->next;
                cur->next = NULL;
                cur = head2;
                for (int i = 1; i < sublen && cur && cur->next; ++i)
                    cur = cur->next;
                ListNode *next = NULL;
                if (cur)
                    next = cur->next, cur->next = NULL;
                cur = next;
                ListNode *node = merge(head1, head2);
                pre->next = node;
                while (pre->next)
                    pre = pre->next;
            }
        }
        return dummy->next;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值