148. Sort List
problem description
Input: 4->2->1->3
Output: 1->2->3->4Input: -1->5->3->4->0
Output: -1->0->3->4->5algorithm thought
code
/**
* 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;
else if(head->next->next==NULL){
ListNode* tmp=head->next;
head->next=NULL;
return merge(head,tmp);
}else{
ListNode* mid=head,*fast=head;
while(fast->next&&fast->next->next){
fast=fast->next->next;
mid=mid->next;
}
cout<<mid->val<<' ';
fast=mid->next;
mid->next=NULL;
return merge(sortList(head),sortList(fast));
}
return NULL;
}
ListNode* merge(ListNode* l1,ListNode* l2){
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
if(l1->val<l2->val){
l1->next=merge(l1->next,l2);
return l1;
}else{
l2->next=merge(l1,l2->next);
return l2;
}
return NULL;
}
};algorithm analysis
Last updated