Accepted C - 4ms, Tail-Call recursive - to avoid stack overflow


  • 0
    D
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    
    void mergeTwoListsAccu(struct ListNode* l1Cur, struct ListNode* l2Cur, struct ListNode* result) {
        
        if (l1Cur == NULL) {
                result->next = l2Cur; 
                return;
        }
        
        if (l2Cur == NULL) {
                result->next = l1Cur; 
                return;
        }
    
        if(l1Cur->val <= l2Cur->val) {
                result->next = l1Cur;
                return mergeTwoListsAccu(l1Cur->next, l2Cur, result->next);
        } else {
                result->next = l2Cur;
                return mergeTwoListsAccu(l1Cur, l2Cur->next, result->next);
        } 
        
        
    };
    
    struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode* result;
        
        if(l1 == NULL) return result = l2;
        if(l2 == NULL) return result = l1;
        
        if (l1->val < l2->val) {
            // Initialize result, otherwise result is NULL when calling mergeTwoListsAccu
            result = l1; 
            mergeTwoListsAccu(l1->next, l2, result);
        } else  {
            // Initialize result, otherwise result is NULL when calling mergeTwoListsAccu
            result = l2;
            mergeTwoListsAccu(l1, l2->next, result);
        }
        
        
        return result;
        
    }

Log in to reply
 

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