给你链表的头结点 head
,请将其按 升序 排列并返回 排序后的链表 。
示例 1:
输入:head = [4,2,1,3] 输出:[1,2,3,4]
示例 2:
输入:head = [-1,5,3,4,0] 输出:[-1,0,3,4,5]
示例 3:
输入:head = [] 输出:[]
冒泡排序:o(n^2),会超时。
/**
* 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* sortList(ListNode* head) {
if (head == NULL)
return head;
ListNode* p;
bool change = true;
while (p != head->next && change) {
ListNode* q = head;
change = false;
for (; q->next && q->next != p; q = q->next) {
if (q->val > q->next->val) {
swap(q->val, q->next->val);
change = true;
}
}
p=q;
}
return head;
}
};
归并排序: o(nlogn)
1、递归二分列表:用p->next->next做判断,p每次循环往后挪两位,q每次循环往后挪一位,这样循环到结尾时,q正好指向中位前一位。从此处截断队列,前后分别再次进入二分循环。
2、前半段和后半段进入两条链表merge的函数:
- 判断是否为空,一条为空则直接返回另一条链表
- 非空判断两条链表的头,小值链表作为原始链表,另一条链表跟其比对,退化为两条链表比大小插入。
/**
* 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* sortList(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
ListNode *fast = head, *slow = head;
while (fast->next != NULL && fast->next->next) {
fast = fast->next->next;
slow = slow->next;
}
fast = slow->next;
slow->next = NULL;
fast = sortList(fast);
slow = sortList(head);
return merge(fast, slow);
}
ListNode* merge(ListNode* head1, ListNode* head2) {
if (head1 == NULL)
return head2;
if (head2 == NULL)
return head1;
ListNode *res, *p;
if (head1->val > head2->val) {
res = head2;
head2 = head2->next;
} else{
res = head1;
head1 = head1->next;
}
p = res;
while (head1 != NULL && head2 != NULL) {
if (head1->val > head2->val) {
p->next = head2;
head2 = head2->next;
} else {
p->next = head1;
head1 = head1->next;
}
p = p->next;
}
if (head1!=NULL) p->next=head1;
else if (head2!=NULL) p->next=head2;
return res;
}
};