445. Add Two Numbers II。

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7


这个题跟Add Two Numbers是一样的,但是这个是需要从链表的最后面开始进行相加。我的思路就是使用栈的特性,遍历两个链表,然后分别将两个链表中的内容存放到两个栈中,然后再根据栈中的数据分别出栈,这样每次出栈的元素的顺序就是原先链表从后往前的顺序。再使用跟之前那个一样的算数体系,使用一个变量保存两个数的总和,一个变量保存进位的数值。不断的创建新的节点,这里需要使用头插法来连接链表。

#include <iostream>
#include <stack>
using namespace std;

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

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

        ListNode* result = new ListNode(0);
        stack<int> nodes1;
        stack<int> nodes2;
        int carry = 0;
        int sum;

        while(l1 || l2) {

            if(l1) {
                nodes1.push(l1->val);
                l1 = l1->next;
            }

            if(l2) {
                nodes2.push(l2->val);
                l2 = l2->next;
            }
        }

        int n1,n2;
        while(!nodes1.empty() || !nodes2.empty()) {//因为两个栈的元素一样多


            if(nodes1.empty()) {
                n1 = 0;
            } else {
                n1 = nodes1.top();
                nodes1.pop();
            }

            if(nodes2.empty()) {
                n2 = 0;
            } else {
                n2 = nodes2.top();
                nodes2.pop();
            }

            //cout << n1 << "," << n2 << endl;


            sum = n1 + n2 + carry;

            //cout << "sum:" << sum << endl;

            carry = sum / 10;//进的位数

            result->val = sum % 10;//最后面一个节点赋值
            ListNode* node = new ListNode(0);
            node->next = result;
            result = node;
        }

        if(carry) {
            result->val = carry;
            return result;
        } else {
            return result->next;
        }
    }
};

int main() {
    Solution s;


    ListNode node1(7);
    ListNode node2(2);
    ListNode node3(4);
    ListNode node4(3);

    ListNode node5(5);
    ListNode node6(6);
    ListNode node7(4);

    node1.next = &node2;
    node2.next = &node3;
    node3.next = &node4;

    node5.next = &node6;
    node6.next = &node7;

    ListNode* p = s.addTwoNumbers(&node1,&node5);
    while(p) {
        cout << p->val << endl;
        p = p->next;
    }

}


运行结果可能有误差。

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值