给你链表的头结点 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
### 解题思路
归并排序,不过一条链转换成两条链这块,想了一会,刚开始一直没转弯,死脑筋觉得一条链上类似数组一样操作就可以,写起来乱糟糟的,后来理清思路,只要遇到一条链,就切割成两条,整体的思路瞬间清晰了许多。
### 代码
```cpp
/**
* 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 == nullptr) {
return head;
}
// only one
if (head->next == nullptr) {
return head;
}
// only two
if (head->next->next == nullptr) {
if (head->val > head->next->val) {
int val = head->val;
head->val = head->next->val;
head->next->val = val;
}
return head;
}
ListNode* mid = find_mid(head);
ListNode* second = mid->next;
mid->next = nullptr;
ListNode* left = sortList(head);
ListNode* right = sortList(second);
ListNode* new_head = nullptr;
ListNode* tail = nullptr;
if (left->val < right->val) {
new_head = left;
left = left->next;
} else {
new_head = right;
right = right->next;
}
new_head->next = nullptr;
tail = new_head;
while (left || right) {
if (left && right) {
if (left->val < right->val) {
tail->next = left;
left = left->next;
} else {
tail->next = right;
right = right->next;
}
} else if (left) {
tail->next = left;
left = left->next;
} else if (right) {
tail->next = right;
right = right->next;
}
tail = tail->next;
}
tail->next = nullptr;
return new_head;
}
ListNode* find_mid(ListNode* head) {
ListNode* mid = head;
ListNode* last = head;
while (last->next != nullptr) {
last = last->next;
if (last->next == nullptr) {
break;
}
last = last->next;
mid = mid->next;
}
return mid;
}
};
```