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

题目大意:

给定两个链表,求各项相加的和,大于10的向下一个节点进位,返回结果链表。

思路:

1、将链表对应的值相加,得到的sum值对10求余求得val,将val和carry的值进行相加并对10求余,将carry的值置为(al+carry)/10。这一步的目的是防止出现1+9的情况导致进位。

2、sum/10的值加入控制进位多少的变量carry。

3、如果两条链表不一样长就得将还未就加入结果链表的链表加入到结果链表中去。

代码:

#include <iostream>
#include <cstdlib>

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

class Solution {
public :
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        
        ListNode *pTemp1 = l1, *pTemp2 = l2, *pTemp3;
        int sum = 0, carry = 0, val;
        
        while (pTemp1 != nullptr && pTemp2 != nullptr) {
            sum = pTemp1->val + pTemp2->val;
            val = sum % 10;
            if (result) {
                pTemp3->next = new ListNode((val + carry) % 10);
                carry = (val + carry) / 10;
                pTemp3 = pTemp3->next;
            } else {
                result = new ListNode((val + carry) % 10);
                carry = (val + carry) / 10;
                pTemp3 = result;
            }
            carry += sum / 10;
            pTemp1 = pTemp1->next;
            pTemp2 = pTemp2->next;
        }
        
        while (pTemp1) {
            pTemp3->next = new ListNode((pTemp1->val + carry) % 10);
            carry = (pTemp1->val + carry) / 10;
            pTemp1 = pTemp1->next;
            pTemp3 = pTemp3->next;
        }
        
        while (pTemp2) {
            pTemp3->next = new ListNode((pTemp2->val + carry) % 10);
            carry = (pTemp2->val + carry) / 10;
            pTemp2 = pTemp2->next;
            pTemp3 = pTemp3->next;
        }
        
        if (carry) {
            pTemp3->next = new ListNode(carry);
        }
        
        return result;
    }
private :
    ListNode *result = nullptr;
};

int main(int argc, char *argv[])
{
    Solution s;
    ListNode *l1 = new ListNode(1);
    ListNode *l2 = new ListNode(9);
    l2->next = new ListNode(9);

    ListNode *l3 = s.addTwoNumbers(l1, l2);
    
    for (ListNode *p = l3; p != nullptr; p = p->next) {
        std::cout << p->val << " ";
    }
    std::cout << std::endl;
    
    return EXIT_SUCCESS;


posted @ 2016-03-27 15:55  Jung_zhang  阅读(125)  评论(0编辑  收藏  举报