Sort a linked list in
O
(
n
log
n
) time using constant space complexity.
题目要求:对一个链表进行归并排序。
基本思想:
1:利用归并排序的整体思想
2:找到一个链表的中间节点的方法
3:合并两个已排好序的链表为一个新的有序链表
基本思想:
1:利用归并排序的整体思想
2:找到一个链表的中间节点的方法
3:合并两个已排好序的链表为一个新的有序链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* findMid(ListNode* head){
if(head==NULL || head->next==NULL) return head;
ListNode* start=head;
ListNode* forword=head;
while(forword->next!=NULL && forword->next->next!=NULL){
start=start->next;
forword=forword->next->next;
}
return start;
}
ListNode* merge(ListNode* a, ListNode* b){
if(a==NULL && b==NULL) return NULL;
if(a==NULL) return b;
if(b==NULL) return a;
ListNode* newhead;
if(a->val <= b->val){
newhead=a;
a=a->next;
}
else{
newhead=b;
b=b->next;
}
ListNode* tmp=newhead;
while(a!=NULL && b!=NULL){
if(a->val <= b->val){
tmp->next=a;
a=a->next;
}
else{
tmp->next=b;
b=b->next;
}
tmp=tmp->next;
}
if(a!=NULL)
tmp->next=a;
if(b!=NULL)
tmp->next=b;
return newhead;
}
ListNode* sortList(ListNode* head) {
if(head==NULL || head->next==NULL) return head;
ListNode* mid=findMid(head);
ListNode* newstart=mid->next;
mid->next=NULL;
return merge(sortList(head),sortList(newstart));
}
};