两数相加 II

给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

进阶:

如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。

示例:

输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 8 -> 0 -> 7

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/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> A;
        stack<int> B;
        ListNode* ret = NULL;
        if(l1 == NULL && l2 == NULL)
            return NULL;
        if(l1 == NULL)
            return l2;
        if(l2 == NULL)
            return l1;
        // int countl1 = 0; 
        // int countl2 = 0;
        while(l1)
        {
            //countl1++;
            A.push(l1->val);
            l1 = l1->next;
        }
        while(l2)
        {
            //countl2++;
            B.push(l2->val);
            l2 = l2->next;
        }
        int jinwei = 0;
        while(A.size() || B.size())
        {
            int a = 0;
            int b = 0;
            if(A.size())
            {
                a = A.top();
                A.pop();
            }
            if(B.size())
            {
                b = B.top();
                B.pop();
            }
                
             
            
            
            int sum = a + b +jinwei;
            if(sum >= 10)
            {
                jinwei = 1;
            }
            else
            {
                jinwei = 0;
            }
            int cur = sum % 10;
            ListNode* tmp = new ListNode(cur);
            if(ret == NULL)
            {
                ret = tmp;
            }
            else
            {
                tmp->next = ret;
                ret = tmp;
            }
            
        }
        if(jinwei == 1)
        {
            ListNode* tmp = new ListNode(1);
            tmp->next = ret;
            ret = tmp;
        }
        
        return ret;
        
    }
};
发布了1033 篇原创文章 · 获赞 41 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_41791402/article/details/96422361