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

struct ListNode {
    int val;
     ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

/*
    最直白的想法就是将两个字符串翻转, 然后相加,得到的结果再发转
    现在的解法,直接从左到右相加,然后向右进位
*/

class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        
        ListNode* ptr = new ListNode(0);  
        ListNode* head = ptr; 
        int tmp_carry = 0;
        int sum;

        while( l1 || l2 )
        {
             sum = 0;
             if( l1 )
             {
                sum += l1->val;
                l1 = l1->next;
             }

             if( l2 )
             {
                sum += l2->val;
                l2 = l2->next;
             }
        
             ptr->next = new ListNode( (sum + tmp_carry)%10 );  
             ptr = ptr->next;
             tmp_carry = (sum + tmp_carry)/10;
        }

        if( tmp_carry )
        {
             ptr->next = new ListNode( tmp_carry );  
        }
        return head->next;
    }
};

 

posted on 2015-04-13 21:59  听风的日子  阅读(196)  评论(0编辑  收藏  举报