题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* mergeSort(ListNode* left, ListNode* right) {
if (left == right) return left; //当只有一个点的时候,直接返回
auto mid = left;
auto fast = mid;
while (fast->next != right && fast != right) {
fast = fast->next->next;
mid = mid->next;
}//使用快慢指针将链表一分为二
auto rhead = mergeSort(mid->next, right);//先对右边进行排序
mid->next = nullptr;//切割左右链表
auto lhead = mergeSort(left, mid);//然后对左边排序
return merge(lhead, rhead);//假设左右两边是已经排列好的序列,合并左右两边的序列
}
ListNode* merge(ListNode* lhead, ListNode* rhead) {//合并两个链表
auto dummy = new ListNode(-1);
dummy->next = (lhead->val < rhead->val) ? lhead : rhead;
auto pre = dummy;
while (lhead != nullptr && rhead != nullptr) {
if (lhead->val < rhead->val) {
pre->next = lhead;
lhead = lhead->next;
} else {
pre->next = rhead;
rhead = rhead->next;
}
pre = pre->next;
}
if (lhead != nullptr) pre->next = lhead;
if (rhead != nullptr) pre->next = rhead;
return dummy->next;
}
ListNode* sortInList(ListNode* head) {
// write code here
auto p = head;
while (p->next != nullptr) p = p->next; //找到链表的尾节点
auto dummy = new ListNode(-1);
dummy->next = mergeSort(head, p);//归并排序
return dummy->next;
}
};

查看11道真题和解析