排序链表
题目链接:排序链表
/**
* 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) {
if(head == NULL || head->next == NULL){
return head;
}
return mergeSort(head);
}
//归并排序
ListNode* mergeSort(ListNode* pBegin){
//递归的出口(终止条件)
if(pBegin == NULL || pBegin->next == NULL){
return pBegin;
}
//首先找到中间结点
ListNode* pMid = findMidPointer(pBegin);
//对前半部分进行归并排序
ListNode* la = mergeSort(pBegin);
//对后半部分进行归并排序
ListNode* lb = mergeSort(pMid);
//合并前后两个部分的链表
return mergeList(la,lb);
}
ListNode* findMidPointer(ListNode *start){
//快慢指针,相同七点,快指针走两步,慢指针走一步,那么最后慢指针所指向的就是中间结点
ListNode *fast,*slow,*pre;
fast = slow = start;
pre = slow;
while(fast && fast->next){
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
pre->next = NULL;
return slow;
}
ListNode* mergeList(ListNode* La,ListNode* Lb){
ListNode *p,*q,*r;
p = La;
q = Lb;
ListNode *head = new ListNode(0);
head->next = NULL;
r = head;
while(p&&q){
if(p->val < q->val){
r->next = p;
r = p;
p = p->next;
}else{
r->next = q;
r = q;
q = q->next;
}
}
while(p){
r->next = p;
r = p;
p = p->next;
}
while(q){
r->next = q;
r = q;
q = q->next;
}
r->next = NULL;
return head->next;
}
};