给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
这是一题比较经典的链表题,一般采用归并排序的方式来做
再编写代码时,一般注意以下:
1、想好返回值和传参,传参一般是排序链表的头和尾,本方法采用左闭右开的方式。
2、排序完的链表记得断链,不然会出现拼接阶段重复排序的问题
代码如下:
/**
* 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* merge(ListNode* l1, ListNode* l2)
{
ListNode* head1 = l1;
ListNode* head2 = l2;
ListNode* dummyNode = new ListNode();
ListNode* temp = dummyNode;
while(head1 != nullptr && head2 != nullptr){
if(head1->val < head2->val)
{
temp->next = new ListNode(head1->val);
head1 = head1->next;
temp = temp->next;
}
else
{
temp->next = new ListNode(head2->val);
head2 = head2->next;
temp = temp->next;
}
}
while(head1 != nullptr){
temp->next = new ListNode(head1->val);
head1 = head1->next;
temp = temp->next;
}
while(head2 != nullptr){
temp->next = new ListNode(head2->val);
head2 = head2->next;
temp = temp->next;
}
return dummyNode->next;
}
//左开右闭原则
ListNode* sortList(ListNode* begin, ListNode* end)
{
if(begin == nullptr){
return begin;
}
if(begin->next == end){
begin->next = nullptr;
return begin;
}
ListNode* temp = begin;
ListNode* mid = begin;
while(temp != end){
temp = temp->next;
if(temp != end) temp = temp->next;
mid = mid->next;
}
ListNode* head1 = sortList(begin, mid);
ListNode* head2 = sortList(mid, end);
return merge(head1, head2);
}
ListNode* sortList(ListNode* head) {
return sortList(head, nullptr);
}
};