题解 | #单链表的排序#
单链表的排序
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* marge(ListNode* Head1, ListNode* Head2)
{
if(Head1 == nullptr)
{
return Head2;
}
if(Head2 == nullptr)
{
return Head1;
}
ListNode* head = new ListNode(0);
ListNode* cur = head;
while(Head1 && Head2)
{
if(Head1->val <= Head2->val)
{
cur->next = Head1;
Head1 = Head1->next;
}
else {
cur->next = Head2;
Head2 = Head2->next;
}
cur = cur->next;
}
if(Head1)
{
cur->next = Head1;
}
if(Head2)
{
cur->next = Head2;
}
return head->next;
}
ListNode* sortInList(ListNode* head) {
if(head == nullptr || head->next == nullptr)
return head;
ListNode* left = head;
ListNode* mid = head->next;
ListNode* right = head->next->next;
while(right != nullptr && right->next != nullptr)
{
left = left->next;
mid = mid->next;
right = right->next->next;
}
left->next = nullptr;
return marge(sortInList(head), sortInList(mid));
}
};
凡岛公司福利 297人发布