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.

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


代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* res, *L1=l1, *L2=l2, *temp;
    while (L1&&L2) {
        L1->val=L2->val=L1->val+L2->val;
        L1 = L1->next;
        L2 = L2->next;
    }
    res = (L1) ? l1 : l2;
    temp=res;
    while (temp) {
        if (temp->val>=10) {
            if (!temp->next) 
            temp->next = (struct ListNode*)calloc(1,sizeof(struct ListNode));
            temp->val-=10;
            temp->next->val+=1;
        } 
        temp = temp->next;
    }
    return res;
}


posted @ 2017-02-28 18:38  壹言  阅读(100)  评论(0编辑  收藏  举报