Struck in question two in C


  • 0
    S
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode *temp1=l1;
    struct ListNode *temp2=l2;
    struct ListNode *n= (struct ListNode *)malloc(sizeof(struct ListNode));
    int carry=0,sum=0,r,count=0;
    struct ListNode *h1,*h2;
    struct ListNode* head=NULL;
    h1=reverse(temp1);
    h2=reverse(temp2);
    while(h1!=NULL && h2!=NULL)
    {
        sum=(h1->val+h2->val+carry);
        if(sum>9)
        {
            while(sum>0)
            {
                r=sum%10;
                count++;
                if(count==1)
                {
                    n->val=r;
                }
                else if(count==2)
                {
                    carry=r;
                    break;
                }
                sum=sum/10;
            }
        }
        else{
            carry=0;
            n->val=sum;
        }
        n->next=NULL;
        if(head==NULL)
            {
             head=n;
    	    }
        h1=h1->next;
        h2=h2->next;
    }
    n->next=NULL;
    return head;
    }
    

    this is the code i had written.But here when i return head value it is going to last node of list instead of first.please help me out.


  • 0
    L

    i think you should initialize head at first like this:

    struct ListNode* head=n;
    

    Since the pointer of n has moved on.


Log in to reply
 

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