Why my solution failed with some cases? I can't fix it.


  • 0
    A
    typedef struct ListNode _ListNode;
    
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        _ListNode * p1 = l1;
        _ListNode * p2 = l2;
        _ListNode * head = NULL;
        _ListNode * tail = NULL;
    
        int sum = 0;
        int nextbit = 0;
        while (p1 && p2)
        {
            sum = p1->val + p2->val + nextbit;  
            nextbit = sum / 10;
        
            _ListNode * ptemp = (_ListNode*)malloc(sizeof(_ListNode));
            ptemp->val = sum % 10;
    
            if (head == NULL)
            head = ptemp;
    
            if (tail == NULL)
            {
                tail = ptemp;
            }
            else
            {
                tail->next = ptemp;
                tail = ptemp;
            }
        
            p1 = p1->next;
            p2 = p2->next;
        }
    
        _ListNode * pLeft = NULL;
        if (p1)
            pLeft = p1;
        
        if (p2)
           pLeft = p2;
    
        while (pLeft)
        {
            sum = pLeft->val + nextbit;
            nextbit = sum / 10;
            _ListNode * ptemp = (_ListNode*)malloc(sizeof(_ListNode));
            ptemp->val = sum % 10;
        
            if (tail == NULL)
            {
                tail = ptemp;
            }
            else
            {
                tail->next = ptemp;
                tail = ptemp;
            }
    	
            pLeft = pLeft->next;
        }
    
        return head;
    }

  • 1
    T

    you must initialise the pointer in NULL:
    _ListNode * ptemp = (_ListNode*)malloc(sizeof(_ListNode));
    this line,because tail pointer holds the address is not NULL,maybe have some mistake in process of output.

    then,you don't consider the case : p1 == NULL , p2 == NULL, but nextbit ! = 0;


  • 0
    A

    Thank you very much! When I failed with the case "[5] [5]", I have known that I missed this case. Finally, my solution passed!


Log in to reply
 

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