2. Add Two Numbers

2017-01-04  本文已影响0人  _SANTU_

You are given two linked lists representing two non-negative numbers. 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.

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

C++ version:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int carry = 0;
        int sumOfOne = l1->val + l2->val + carry;
        carry = sumOfOne/10;
        sumOfOne %= 10;
        struct ListNode *result = new struct ListNode(sumOfOne);
        struct ListNode *cur = result;
        l1 = l1->next;
        l2 = l2->next;
        
        while(l1 || l2){
            if(l1&&l2){
                sumOfOne = l1->val + l2->val + carry;
                l1 = l1->next;
                l2 = l2->next;
            }else if(l1==NULL){
                sumOfOne = l2->val + carry;
                l2 = l2->next;
            }else if(l2==NULL){
                sumOfOne = l1->val + carry;
                l1 = l1->next;
            }
            carry = sumOfOne/10;
            sumOfOne %= 10;
            // printf("sumOfOne: %d\n",sumOfOne);
            struct ListNode *oneNode = new struct ListNode(sumOfOne);
            cur->next = oneNode;
            cur = cur->next;
            // printf("cur->val: %d\n",cur->val);
        }
        if(carry==1){
            struct ListNode *oneNode = new struct ListNode(carry);
            cur->next = oneNode;
            cur = cur->next;
        }
        return result;
    }
};
上一篇下一篇

猜你喜欢

热点阅读