导航

LeetCode 2. Add Two Numbers

Posted on 2017-01-08 23:16  CSU蛋李  阅读(140)  评论(0编辑  收藏  举报

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

这个题目需要考虑的是特殊情况如2->3+8->6,或者2->3+8->6->9->9

 

/**
 * 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) {
        ListNode *p_retNode = l1;
        ListNode *p_preNode = NULL;
        int tag = 0;
        while (NULL != l1&&NULL != l2)
        {
            l1->val += l2->val + tag;
            tag = 0;
            if (l1->val >= 10)
            {
                tag = 1;
                l1->val -= 10;
            }
            p_preNode = l1;
            l1 = l1->next;
            l2 = l2->next;
        }
        if (NULL != l1)
        {
            while (0!=tag&&l1)
            {
                l1->val += tag;
                tag = 0;
                if (l1->val >= 10)
                {
                    l1->val -= 10;
                    tag = 1;
                    p_preNode = l1;
                    l1 = l1->next;
                }
            }
            if (NULL == l1&&1==tag)
            {
                l1 = new ListNode(1);
                p_preNode->next = l1;
            }
        }
        if (NULL != l2)
        {
            p_preNode->next=l2;
            while (NULL != l2&&tag != 0)
            {
                l2->val += tag;
                tag = 0;
                if (l2->val >= 10)
                {
                    l2->val -= 10;
                    tag = 1;
                    p_preNode = l2;
                    l2 = l2->next;
                }
            }
            if (NULL == l2 && 1 == tag)
            {
                l2 = new ListNode(1);
                p_preNode->next = l2;
            }
        }
        if (NULL == l1&&NULL == l2&&tag)
        {
            l1 = new ListNode(1);
            p_preNode->next = l1;
        }

        return p_retNode;
    }
};