题解 | #单链表的排序#
单链表的排序
http://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
利用归并排序来求解
首先用快慢指针来找到链表的中点,把链表分为前后两部分,然后对自链表进行排序
最后把两个已排好序的链表就行合并
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* merge(ListNode* head1,ListNode* head2){//合并两条排序的链表
if(head1==NULL) return head2;
if(head2==NULL) return head1;
ListNode *newhead=new ListNode(0),*p=newhead;
while(head1&&head2){
if(head1->val<head2->val){
p->next=head1;
p=p->next;
head1=head1->next;
}else{
p->next=head2;
p=p->next;
head2=head2->next;
}
}
while(head1){
p->next=head1;
p=p->next;
head1=head1->next;
}
while(head2){
p->next=head2;
p=p->next;
head2=head2->next;
}
return newhead->next;
}
ListNode* sort(ListNode *head){ //归并排序
if(head==NULL||head->next==NULL) return head;
ListNode *fast=head,*slow=head,*pre;
while(fast &&fast->next){ //找到中点
fast=fast->next->next;
pre=slow;
slow=slow->next;
}
pre->next=NULL;//head--pre是前半部分
ListNode *head1=sort(slow);//slow--NULL是后半部分
ListNode* head2=sort(head);
return merge(head1,head2);
}
ListNode* sortInList(ListNode* head) {
// write code here
return sort(head);
}
};