Add two numbers,i can’t find bug,seem to be right?


  • 0
    L
    class Solution {public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        int add=0;
        if(l1==NULL&&l2==NULL)return NULL;
        ListNode *head=NULL;
        ListNode *p=head;
        int a,b=0;
        int sum;
        while(l1!=NULL||l2!=NULL){
            if(l1!=NULL)a=l1->val;
            else a=0;
            if(l2!=NULL)b=l2->val;
            else b=0;
            sum=a+b+add;
            if(sum>9){
                sum=sum-10;
                add=1;
            }
            else add=0;
            p=new ListNode(sum);
            p=p->next;
            if(l1)l1=l1->next;
            if(l2)l2=l2->next;
        }
        if(add==1)p=new ListNode(1);
        return head;
    }
    

    };

    input{0}{0}return NULL


  • 1
    S

    hi!

    I think this part of your code is wrong:

        p=new ListNode(sum);
        p=p->next;
    

    you should add the new node into your link.
    try this way:
    ListNode* tail = new ListNode(sum);
    p->next = tail;
    p = p->next;

    it should be work;

    thanks!


  • 0
    L

    I HAVE FOUND THE BUG.THANK YOU ALL THE SAME


Log in to reply
 

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