题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
if (!head || !head->next) {
return head;
}
ListNode *bef = nullptr;
auto slow = head;
auto fast = head;
while (fast && fast->next) {
bef = slow;
slow = slow->next;
fast = fast->next->next;
}
bef->next = nullptr;
head = sortInList(head);
slow = sortInList(slow);
ListNode *res = nullptr, **now = &res;
while (head && slow) {
if (head->val < slow->val) {
*now = head;
head = head->next;
} else {
*now = slow;
slow = slow->next;
}
now = &((*now)->next);
}
*now = head ? head: slow;
return res;
}
};
思路:链表排序,加上Onlogn的时间复杂度要求,那只能用归并了。
具体细节上:
* 快慢指针,避免多次遍历。
* bef指针,断开需要递归的两个子链表。
* 归并时使用二级指针,可以不额外使用空间就实现归并。
查看5道真题和解析