Untitled

 avatar
unknown
c_cpp
2 years ago
1.7 kB
7
Indexable
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        ListNode *tmp,*prev,*curr,*t2;
        if(!(head->next)) return head;
        else if(!(head->next->next)){
            if(head->val<=head->next->val) return head;
            else {
                tmp = head;
                head = head->next;
                head->next = tmp;
                tmp->next = NULL;
                return head;
            }
        }
        prev =tmp=t2= head;
        curr = head->next;
        if(curr->val < prev->val){
            head = curr;
            curr = curr->next;
            head->next = prev;
            prev->next = NULL;

        }
        else{
            prev =curr;
            curr= curr->next;
            prev->next = NULL;
        }
        
        while(curr){
          //  tmp=head;
          // t2=tmp;
        while((tmp) && (tmp->val < curr->val) ){
            t2=tmp;
            tmp = tmp->next;
        }
        if(!tmp){
          
            t2->next = curr;
          
            curr=curr->next;
            t2->next->next = NULL;
           
        }else{
            t2->next = curr;
            curr = curr->next;
            t2->next->next = tmp;
           

        }
         t2=tmp=head;

        }
      
     return head;
        
    }
};
Editor is loading...