Clear C++ solution


  • 0
    C
    void insert(ListNode *node, ListNode*& head)
    {
        if(!head)
        {
            head = node;
            head->next = NULL;
            return;
        }
    
        if(node->val < head->val)
        {
            node->next = head;
            head = node;
            return;
        }
        
        ListNode *pre = NULL;
        ListNode *p = head;
        while(p)
        {
            pre = p;
            p = p->next;
            if(p && pre->val<=node->val && node->val <p->val)
            {
                pre->next = node;
                node->next = p;
                return;
            }
        }
        pre->next = node;
        node->next = NULL;
        return;
    }
    ListNode* insertionSortList(ListNode* head) {
        
        ListNode *res = NULL;
        ListNode* p = head;
        while(p)
        {
            ListNode* tmp = p->next;
            insert(p,res);
            p = tmp;
            
        }
        return res;
        
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.