C solution providing different results with run than with submit


  • 0
    C

    This is my solution:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    #include <stdlib.h>
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode *answer, *answerHead;
        int sum;
        int carry = 0;
        
        answer = malloc(sizeof(struct ListNode));
        answerHead = answer;
        while(l1 || l2){
            sum = 0;
            
            if(l1){
                sum += l1 -> val;
                l1 = l1 -> next;
            }
            if(l2){
                sum += l2 -> val;
                l2 = l2 -> next;
            }
            
            sum += carry;
            if(sum > 9){
                carry = 1;
            }else{
                carry = 0;
            }
            sum = sum % 10;
            answerHead -> val = sum;
            
            if(l1 || l2){
                answerHead -> next = malloc(sizeof(struct ListNode));
                answerHead = answerHead -> next;
                answerHead -> next = NULL;
            }
        }
        if(carry){
            answerHead -> next = malloc(sizeof(struct ListNode));
            answerHead = answerHead -> next;
            answerHead -> val = 1;
            answerHead -> next = NULL;
        }
        return answer;
    }
    

    When I submit the solution, it fails on [1][0], saying that the output was [1,0] instead of the expected [1]. However, when I run the code I get the expected answer. Whats going on and how can I fix it? Thanks


  • 0
    C

    I found the answer to my own question. I had to set answerHead.next to null at the end of my program regardless of whether or not I needed to carry. I don't know why it worked in run and not on submit however.


Log in to reply
 

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