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 ;
    }
};

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )