Why Is My O(n) C Solution Slower Than Others?


  • 0
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode* itr1 = l1;
        struct ListNode* itr2 = l2;
        struct ListNode* firstnode = NULL;
        struct ListNode* lastnode = NULL;
        struct ListNode* currentnode = NULL;
        int carry = 0;
        for (; itr1 != NULL || itr2 != NULL || carry;) {
            currentnode = (struct ListNode*)malloc(sizeof(struct ListNode));
            currentnode->next = NULL;
            int sum = ((itr1 ? itr1->val : 0) + (itr2 ? itr2->val : 0) + carry);
            currentnode->val = sum%10;
            carry = sum/10;
            
            if (!lastnode) {
                firstnode = currentnode;
                lastnode = currentnode;
            }
            else {
                lastnode->next = currentnode;
                lastnode = currentnode;
            }
             
            if (itr1 != NULL)
                itr1 = itr1->next;
            if (itr2 != NULL)    
                itr2 = itr2->next;
        }
        return firstnode;
    }
    

  • 0
    R

    @simanstar How long did ur code cost? Try to not malloc new memory and save the result to the existent memory.


Log in to reply
 

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