解题思路:
- 本文要求将无序链表进行排序,可以选择归并排序
- 注意:
1.归并分为左右递归和融合模块
/**
* 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* sortList(ListNode* head) {
return sortList(head,nullptr);
}
ListNode* sortList(ListNode* head,ListNode* tail){
// 空结点
if(head==nullptr)return head;
// 单一结点
if(head->next==tail){
// 这里是为了归并融合时的一个结束标志,特别是左半边head->next==mid时要将mid改为nullptr,这样才能标志结束
head->next = nullptr;
return head;
}
//创建快慢指针来寻找分界的中点
ListNode *slow=head,*fast = head;
while(fast!=tail){
slow = slow->next;
fast = fast->next;
if(fast != tail){
fast = fast->next;
}
}
ListNode* mid = slow;
return merge(sortList(head,mid),sortList(mid,tail));
}
// 融合是将两个有序的子序列进行融合
ListNode* merge(ListNode* head1,ListNode* head2){
// 生成的头结点
ListNode* dummyHead = new ListNode(0);
// 生成临时的结点,方便进行迭代
ListNode *temp = dummyHead, *temp1 = head1, *temp2 = head2;
// 选择交替进行插入
while(temp1 != nullptr && temp2 != nullptr){
if(temp1->val <= temp2->val){
temp->next = temp1;
temp1 = temp1->next;
}else{
temp->next = temp2;
temp2 = temp2->next;
}
temp = temp->next;
}
// 如果某一个为空另外一个可以直接插入
if(temp1 !=nullptr){
temp->next = temp1;
}else if(temp2 != nullptr){
temp->next = temp2;
}
return dummyHead->next;
}
};