Leetcode Add Two Numbers II

本文介绍了一种链表数字相加的算法实现,通过使用栈来存储链表中的每个数字,然后逐位进行相加并处理进位,最终得到结果链表。此方法适用于需要对大数进行操作的场景。

题意:将两个以链表形式存储的数字向加,并以链表形式输出。

思路:先按位向加,最后将链表颠倒。

/**
 * 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) {
        stack<int> sl1;
        stack<int> sl2;
        ListNode* next = l1;
        while(next) {
            sl1.push(next->val);
            next = next->next;
        }
        next = l2;
        while(next) {
            sl2.push(next->val);
            next = next->next;
        }
        ListNode* myhead = new ListNode(0);
        next = myhead;
        int c = 0;
        while(!sl1.empty() || !sl2.empty()) {
            int a = 0;
            int b = 0;
            if(!sl1.empty()) {
                a = sl1.top();
                sl1.pop();
            }
            if(!sl2.empty()) {
                b = sl2.top();
                sl2.pop();
            }
            
           
            ListNode* temp = new ListNode((a + b + c) % 10);
             c = (a + b + c) / 10;
            next->next = temp;
            next = temp;
        }
        
        if(c) {
            ListNode* temp = new ListNode(c);
            next->next = temp;
            next = temp;
        }
        
        //show the result
       
        
        // reverse
        next = myhead->next;
        ListNode* pre = NULL;
        while(next) { cout << next->val << endl;
            ListNode* temp = next->next;
            next->next = pre;
            pre = next;
            next = temp;
            
        }
        
        return pre;
    }
};


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值