2. Add Two Numbers

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.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* l = (struct ListNode*)malloc(sizeof(struct ListNode));
    int last_sum = l1->val + l2->val,this_sum;
    l->val = last_sum % 10;
    struct listNode* head = l;
    l1 = l1->next;
    l2 = l2->next;
    while(l1 && l2){
        struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
        this_sum = l1->val + l2->val;
        node->val = (last_sum/10 + this_sum)%10;
        last_sum = last_sum/10 + this_sum;
        l->next = node;
        l = node;
        l1 = l1->next;
        l2 = l2->next;
    }
    struct ListNode* l12 = (struct ListNode*)malloc(sizeof(struct ListNode));
    l12 = NULL;
    if(l1) l12 = l1;
    if(l2) l12 = l2;
    if(l12){
        if(last_sum < 10){
            l->next = l12;
            return head;
        }
        else{
            while(l12){
                struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
                node->val = (last_sum/10 + l12->val)%10;
                last_sum = last_sum/10 + l12->val;
                l->next = node;
                l = node;
                l12 = l12->next;
            }
        }
    }
    if(last_sum/10){
        struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
        node->val = last_sum/10;
        l->next = node;
        l = node;
    }
    l->next = NULL;
    return head;
}


posted @ 2018-03-11 20:06  ACLJW  阅读(89)  评论(0编辑  收藏  举报