leetcode 2. Add Two Numbers

 

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

注意要进位和链表尾插法

 

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        
        if(l1 == NULL) return l2;
        if(l2 == NULL) return l1;
        ListNode* tail = new ListNode(0);
        ListNode* pre = tail;
        int flag = 0;
        while(l1!= NULL || l2!= NULL)
        {
            int val1 = 0;
            int val2 = 0;
            if(l1 != NULL)
            {
                val1 = l1->val;
                l1 = l1->next;
            }
            if(l2 != NULL)
            {
                val2 = l2->val;
                l2 = l2->next;
            }
            int sum = val1 + val2 + flag;
            ListNode* node = new ListNode(sum%10);
            flag = sum/10;
            pre->next = node;
            pre = node;
            
        }
        if (flag == 1)
        {
            ListNode* node = new ListNode(1);
            pre->next = node;
        }
        return tail->next;
    }
};

  

posted @ 2016-07-07 21:09  路萧  阅读(146)  评论(0编辑  收藏  举报