[LeetCode] 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

Solutions:

/**
 * 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 *ans = NULL, *end = NULL, *num1 = l1, *num2 = l2;
        int carry = 0, sum = 0;
        while(true)
        {
            if(num1 != NULL)
            {
                if(num2 != NULL)
                {
                    sum = num1 -> val + num2 -> val + carry;
                    carry = sum / 10;
                    if(ans == NULL)
                    {
                        ans = new ListNode(sum % 10);
                        end = ans;
                    }
                    else
                    {
                        end -> next = new ListNode(sum % 10);
                        end = end -> next;
                    }
                    num1 = num1 -> next;
                    num2 = num2 -> next;
                }
                else
                {
                    sum = num1 -> val + carry;
                    carry = sum / 10;
                    if(ans == NULL)
                    {
                        ans = new ListNode(sum % 10);
                        end = ans;
                    }
                    else
                    {
                        end -> next = new ListNode(sum % 10);
                        end = end -> next;
                    }
                    num1 = num1 -> next;
                }
            }
            else
            {
                if(num2 != NULL)
                {
                    sum = num2 -> val + carry;
                    carry = sum / 10;
                    if(ans == NULL)
                    {
                        ans = new ListNode(sum % 10);
                        end = ans;
                    }
                    else
                    {
                        end -> next = new ListNode(sum % 10);
                        end = end -> next;
                    }
                    num2 = num2 -> next;
                }
                else
                {
                    if(carry == 1)
                    {
                        end -> next = new ListNode(1);
                        end = end -> next;
                    }
                    break;
                }
            }
        }
        
        return ans;
    }
};
posted @ 2014-03-11 20:07  xchangcheng  阅读(141)  评论(0编辑  收藏  举报