题解 | #单链表的排序#
单链表的排序
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* sortInList(ListNode* head) {
// write code here
if (!head || !head->next) {
return head;
}
ListNode* fast = head;
ListNode* slow = head;
ListNode* pre_slow = nullptr;
while (fast && fast->next) {
fast = fast->next->next;
pre_slow = slow;
slow = slow->next;
}
pre_slow->next = nullptr;
return merge2List(sortInList(head), sortInList(slow));
}
private:
ListNode* merge2List(ListNode* head1, ListNode* head2) {
if (!head1) {
return head2;
}
if (!head2) {
return head1;
}
ListNode* new_head = new ListNode(-1);
ListNode* res_head = new_head;
new_head->next = head1;
while (head1 && head2) {
if (head1->val < head2->val) {
new_head->next = head1;
head1 = head1->next;
new_head = new_head->next;
} else {
new_head->next = head2;
head2 = head2->next;
new_head = new_head->next;
}
}
if (head1) {
new_head->next = head1;
}
if (head2) {
new_head->next = head2;
}
return res_head->next;
}
};
查看6道真题和解析