Insertion Sort List @LeetCode
PROBLEM :
Sort a linked list using insertion sort.
--------------------------------------------------------------------------------
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* insertionSortList(ListNode* head) {
if(head==NULL||head->next==NULL)
return head ;
ListNode* list=NULL ;
ListNode* temp ;
while(head){
temp=head->next ;
head->next=NULL ;
list=InplaceSort(list,head) ;
head=temp ;
}
return list ;
}
ListNode* InplaceSort(ListNode* list,ListNode* node){
if(list==NULL)
return node ;
if(list->val>node->val){
node->next=list ;
list=node ;
return list ;
}
ListNode* temp=list ;
while(temp->next){
if(temp->next->val>node->val){
node->next=temp->next ;
temp->next=node ;
return list ;
}
temp=temp->next ;
}
temp->next=node ;
node->next=NULL ;
return list ;
}
};
---------------------------------------------------------------------------------
Sort a linked list using insertion sort.
--------------------------------------------------------------------------------
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* insertionSortList(ListNode* head) {
if(head==NULL||head->next==NULL)
return head ;
ListNode* list=NULL ;
ListNode* temp ;
while(head){
temp=head->next ;
head->next=NULL ;
list=InplaceSort(list,head) ;
head=temp ;
}
return list ;
}
ListNode* InplaceSort(ListNode* list,ListNode* node){
if(list==NULL)
return node ;
if(list->val>node->val){
node->next=list ;
list=node ;
return list ;
}
ListNode* temp=list ;
while(temp->next){
if(temp->next->val>node->val){
node->next=temp->next ;
temp->next=node ;
return list ;
}
temp=temp->next ;
}
temp->next=node ;
node->next=NULL ;
return list ;
}
};
---------------------------------------------------------------------------------
Comments
Post a Comment