Merge Sort for Linked Lists
PROBLEM :
Sort a linked list in O(n log n) time using constant space complexity.
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/**
* 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* a=NULL ;
ListNode* b=NULL ;
divide2half(head,&a,&b) ;
a=sortList(a) ;
b=sortList(b) ;
head=MeargeSort(a,b) ;
return head ;
}
void divide2half(ListNode* head,ListNode* *a,ListNode* *b){
ListNode* slow,*fast ;
slow=head ;
fast=head->next ;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next ;
slow=slow->next ;
}
(*a)=head ;
(*b)=slow->next ;
slow->next=NULL ;
}
ListNode* MeargeSort(ListNode* a,ListNode* b){
ListNode* final=NULL ;
if(a==NULL)
return b ;
if(b==NULL)
return a ;
if(a->val<b->val){
final=a ;
final->next=MeargeSort(a->next,b) ;
}
else{
final=b ;
final->next=MeargeSort(a,b->next) ;
}
return final ;
}
};
---------------------------------------------------------------------------------
Sort a linked list in O(n log n) time using constant space complexity.
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/**
* 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* a=NULL ;
ListNode* b=NULL ;
divide2half(head,&a,&b) ;
a=sortList(a) ;
b=sortList(b) ;
head=MeargeSort(a,b) ;
return head ;
}
void divide2half(ListNode* head,ListNode* *a,ListNode* *b){
ListNode* slow,*fast ;
slow=head ;
fast=head->next ;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next ;
slow=slow->next ;
}
(*a)=head ;
(*b)=slow->next ;
slow->next=NULL ;
}
ListNode* MeargeSort(ListNode* a,ListNode* b){
ListNode* final=NULL ;
if(a==NULL)
return b ;
if(b==NULL)
return a ;
if(a->val<b->val){
final=a ;
final->next=MeargeSort(a->next,b) ;
}
else{
final=b ;
final->next=MeargeSort(a,b->next) ;
}
return final ;
}
};
---------------------------------------------------------------------------------
Comments
Post a Comment