实现链表相加,链表 1为 3->7->2,链表 2 为 2->4,最后生成新的结果链表为 3->9->6

#include <iostream>
#include <stack>

using namespace std;

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

class Solution {
public:
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        if (head1 == nullptr) return head2;
        if (head2 == nullptr) return head1;

        stack<ListNode*> s1;
        stack<ListNode*> s2;

        while (head1 != nullptr) {
            s1.push(head1);
            head1 = head1->next;
        }

        while (head2 != nullptr) {
            s2.push(head2);
            head2 = head2->next;
        }

        int flag = 0;
        ListNode* newHead = nullptr;

        while (!s1.empty() || !s2.empty() || flag > 0) {
            int sum = flag;

            if (!s1.empty()) {
                sum += s1.top()->val;
                s1.pop();
            }

            if (!s2.empty()) {
                sum += s2.top()->val;
                s2.pop();
            }

            flag = sum / 10;
            ListNode* newNode = new ListNode(sum % 10);
            newNode->next = newHead;
            newHead = newNode;
        }

        return newHead;
    }
};

int main() {
    ListNode* head1 = new ListNode(3);
    head1->next = new ListNode(7);
    head1->next->next = new ListNode(2);

    ListNode* head2 = new ListNode(2);
    head2->next = new ListNode(4);

    Solution solution;
    ListNode* result = solution.addInList(head1, head2);

    while (result != nullptr) {
        cout << result->val << " ";
        result = result->next;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值