leetcode#148 排序链表
题目:
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
进阶:
- 你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
示例:
输入: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;
}
};