链表排序用递归归并排序,复杂度nlogn
split链表和插入链表有一个dummy头结点方便很多。
sortlist后记得重新赋值返回的头节点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<ListNode*> split(ListNode* head){
assert(head!=NULL && head->next);
ListNode* dummy=new ListNode(0);
dummy->next=head;
dummy->next=head;
ListNode* p1=dummy;
ListNode* p2=dummy;
while(p2 && p2->next){
p1=p1->next;
p2=p2->next;
if(!p2)
break;
p2=p2->next;
}
ListNode* head2=p1->next;
p1->next=NULL;
return {head,head2};
}
void debug(ListNode* p){
while(p)
printf("%d ",p->val),p=p->next;
printf("\n");
}
ListNode* sortList(ListNode* head) {
if(head==NULL)
return NULL;
if(head->next==NULL){
return head;
}
auto split_ret=split(head);
ListNode*p1=split_ret[0];
ListNode*p2=split_ret[1];
p1=sortList(p1);
p2=sortList(p2);
ListNode* dummy=new ListNode(0);
ListNode* p=dummy;
while(p1 && p2){
if(p1->val<=p2->val){
p->next=p1;
p1=p1->next;
}
else{
p->next=p2;
p2=p2->next;
}
p=p->next;
}
if(p1){
p->next=p1;
}
if(p2){
p->next=p2;
}
return dummy->next;
}
};
这是第二种思路,分成个链表,left,mid,right。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head==NULL || head->next==NULL)
return head;
ListNode* left_dummy=new ListNode(0);
ListNode* mid_dummy=new ListNode(0);
ListNode* right_dummy=new ListNode(0);
int mid_val=find_mid(head)->val;
ListNode *left=left_dummy;
ListNode *mid=mid_dummy;
ListNode *right=right_dummy;
ListNode *p=head;
while(p){
if(p->val<mid_val){
left->next=p;
left=left->next;
}
else if(p->val>mid_val){
right->next=p;
right=right->next;
}
else{
mid->next=p;
mid=mid->next;
}
p=p->next;
}
left->next=NULL;
mid->next=NULL;
right->next=NULL;
left_dummy->next=sortList(left_dummy->next);
right_dummy->next=sortList(right_dummy->next);
ListNode* left_tail=get_tail(left_dummy);
left_tail->next=mid_dummy->next;
mid->next=right_dummy->next;
return left_dummy->next;
}
ListNode * get_tail(ListNode *p){
if(p==NULL)
return NULL;
while(p->next){
p=p->next;
}
return p;
}
ListNode* find_mid(ListNode *head){
ListNode *dummy=new ListNode(0);
dummy->next=head;
ListNode* slow=dummy;
ListNode* fast=dummy;
while(fast->next){
slow=slow->next;
fast=fast->next->next;
if(fast==NULL)
break;
}
return slow;
}
};