add two numbers

question

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    int tmp=0,carry=0;
    struct ListNode* result=NULL;
    struct ListNode* curr=NULL;
    struct ListNode* new=NULL;
    while(l1 && l2){
        tmp=(l1->val)+(l2->val)+carry;
        new=malloc(sizeof(struct ListNode));
        new->val=(tmp%10);
        if(result==NULL){
            result=curr=new;
        }else{
            curr->next=new;
            curr=new;
        }
        carry=tmp/10;
        l1=l1->next;
        l2=l2->next;
    }
    if(l1 || l2){
        struct ListNode* p=(l1?l1:l2);
        while(p){
            tmp=(p->val)+carry;
            new=malloc(sizeof(struct ListNode));
            new->val=(tmp%10);
            curr->next=new;
            curr=new;
            carry=tmp/10;
            p=p->next;
         }
    }
    if(carry){
        new=malloc(sizeof(struct ListNode));
        new->val=carry;
        curr->next=new;
        curr=new;
    }
    curr->next=NULL;
    return result;
}

你可能感兴趣的:(add two numbers)