2. Add Two Numbers

solution1:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
       int a,b,tmp;
    struct ListNode* head, *temp, *tail;
    head = NULL; temp = NULL; tail = NULL;
    a=0;b=0;
    while(l1 || l2)
    {
        if(l1 && l2)
        {
            tmp=l1->val + l2->val;
        }
        else if(l1)
        {
            tmp=l1->val;
        }
        else
        {
            tmp=l2->val;
        }
        
        a = (tmp+b) % 10;
        b = (tmp+b) / 10;
        if(a >= 10)
        {
            temp = (struct ListNode*)malloc(sizeof(struct ListNode)*1);
            temp->val = a-10;
            a = a/10;
            b=0;
            temp->next=NULL;   
            tail->next = temp;
            tail = temp;
        }
        temp = (struct ListNode*)malloc(sizeof(struct ListNode)*1);
        temp->val = a;
        temp->next=NULL;
        if(head==NULL)
        {
            head = temp;
            tail = temp;
        }

        else
        {
            tail->next = temp;
            tail = temp;
        }

        if(l1) l1 = l1->next;
        if(l2) l2 = l2->next;
    }
    if(tmp+b >= 10)
    {
        temp = (struct ListNode*)malloc(sizeof(struct ListNode)*1);
        temp->val = b;
        temp->next=NULL;   
        tail->next = temp;
    }

    return head;
}

你可能感兴趣的:(2. Add Two Numbers)