码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode---Add Two Numbers

时间:2015-01-07 20:54:50      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:leetcode   链表   合并   

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

解决代码:

/**
 * 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) 
    {
        if(l1 == nullptr)
            return l2;
        if(l2 == nullptr)
            return nullptr;
        ListNode* temp1 = l1;
        ListNode* temp2 = l2;
        ListNode* first1 = l1;
        ListNode* first2 = l2;
        int count = 0;
        while(temp1 != nullptr && temp2 != nullptr)
        {
            temp1->val = temp1->val + temp2->val + count;
            count = temp1->val / 10;
            temp1->val = temp1->val%10;
            temp2->val = temp1->val;
            first1 = temp1;
            first2 = temp2;
            temp1 = temp1->next;
            temp2 = temp2->next;
        }
        if(temp2 == nullptr)
        {
            while(temp1 != nullptr)
            {
                temp1->val = temp1->val + count;
                count = temp1->val / 10;
                temp1->val = temp1->val%10;
                if(count == 0)
                    return l1;
                first1 = temp1;
                temp1 = temp1->next;
            }
            if(count != 0)
            {
                ListNode* temp = new ListNode(count);
                first1->next = temp;
            }
            return l1;
        }
        if(temp1 == nullptr)
        {
            while(temp2 != nullptr)
            {
                temp2->val = temp2->val + count;
                count = temp2->val / 10;
                temp2->val = temp2->val%10;
                if(count == 0)
                    return l2;
                first2 = temp2;
                temp2 = temp2->next;
            }
            if(count != 0)
            {
                ListNode* temp = new ListNode(count);
                first2->next = temp;
            }
            return l2;
        }
    }
};


LeetCode---Add Two Numbers

标签:leetcode   链表   合并   

原文地址:http://blog.csdn.net/shaya118/article/details/42499191

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!