题目:
给你链表的头结点 head
,请将其按 升序 排列并返回 排序后的链表 。
示例 1:
输入:head = [4,2,1,3] 输出:[1,2,3,4]
示例 2:
输入:head = [-1,5,3,4,0] 输出:[-1,0,3,4,5]
示例 3:
输入:head = [] 输出:[]
题解:
1、归并排序:
1、如果链表为空或只包含一个节点,直接返回即可。
2、使用快慢指针找到链表的中点,将链表分为两部分。
3、对分割后的两部分链表分别进行递归调用,继续进行归并排序。
4、合并排好序的两个链表,返回合并后的链表。
代码如下:
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head==nullptr||head->next==nullptr) {
return head;
}
ListNode* mid=gitMiddle(head);
ListNode* midnext=mid->next;
mid->next=nullptr;
ListNode* left=sortList(head);
ListNode* right=sortList(midnext);
return merge(left,right);
}
ListNode* gitMiddle(ListNode* head) {
ListNode* fast=head;
ListNode* slow=head;
while(fast->next&&fast->next->next) {
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
ListNode* merge(ListNode* l1,ListNode* l2) {
ListNode* dummyHead=new ListNode(0);
ListNode* curr=dummyHead;
while(l1&&l2) {
if(l1->val<l2->val) {
curr->next=l1;
l1=l1->next;
}
else {
curr->next=l2;
l2=l2->next;
}
curr=curr->next;
}
if(l1) {
curr->next=l1;
l1=l1->next;
}
else {
curr->next=l2;
l2=l2->next;
}
return dummyHead->next;
}
};
2、sort排序:
直接把链表的值用vector存储,然后对值sort排序,再存回来。
代码如下:
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head==nullptr||head->next==nullptr) {
return head;
}
vector<int> temp;
ListNode* curr=head;
while(curr) {
temp.push_back(curr->val);
curr=curr->next;
}
sort(temp.begin(),temp.end());
curr=head;
for(auto c:temp) {
curr->val=c;
curr=curr->next;
}
return head;
}
};