给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
进阶:
你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
示例 2:
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
示例 3:
输入:head = []
输出:[]
提示:
链表中节点的数目在范围 [0, 5 * 104] 内
-105 <= Node.val <= 105
#include <iostream>
using namespace std;
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) {
return sortListEx(head, NULL);
}
ListNode* sortListEx(ListNode* head, ListNode* tail) {
if (head == NULL) {
return head;
}
if (head->next == tail) {
head->next = NULL;
return head;
}
ListNode* slow = head;
ListNode* quick = head;
while (quick != tail) {
slow = slow->next;
quick = quick->next;
if (quick != tail) {
quick = quick->next;
}
}
ListNode* mid = slow;
return mergeTwoLists(sortListEx(head, mid), sortListEx(mid, tail));
}
/* 合并两个有序链表 */
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL && l2 == NULL)
return NULL;
else if (l1 == NULL) {
return l2;
}
else if (l2 == NULL) {
return l1;
}
return mergeTwo(l1, l2);
}
ListNode* mergeTwo(ListNode* l1, ListNode* l2) {
ListNode* pre = new ListNode(0);
ListNode* head = pre;
while (l1 != NULL && l2 != NULL) {
if (l1->val > l2->val) {
if (pre != NULL) {
pre->next = l2;
}
l2 = l2->next;
}
else {
if (pre != NULL) {
pre->next = l1;
}
l1 = l1->next;
}
if (pre->next != NULL) {
pre = pre->next;
}
}
if (l1 == NULL) {
pre->next = l2;
}
else if (l2 == NULL) {
pre->next = l1;
}
return head->next;
}
};