C solution.


  • 0
    N
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    
    void addnode(struct ListNode **l,int a){
        struct ListNode *tmp=NULL,*p=NULL;
        tmp = malloc (sizeof(struct ListNode));
        tmp->val=a;
        tmp->next=NULL;
        if(*l==NULL){
            *l=tmp;
            p=tmp;
        }else{
            for(p=*l;p->next!=NULL;p=p->next);
            p->next=tmp;
        }
    }
    
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    int carry=0,tmpsum=0;
    struct ListNode *L3=NULL;;
    while(l1!=NULL || l2!=NULL){
        tmpsum=carry;
        if(l1!=NULL){
            tmpsum = tmpsum+ l1->val;
            l1=l1->next;
        }
        if(l2!=NULL){
            tmpsum=tmpsum+l2->val;
            l2=l2->next;
        }
        if(tmpsum>9){
           carry=1;
        }else{
           carry=0;
        }
        addnode(&L3,tmpsum%10);
    }
    if(carry){
        addnode(&L3,carry);
    }
    return L3;
    }
    

Log in to reply
 

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