LeetCode 每日一题445. 两数相加 II

445. 两数相加 II

题意

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

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

样例输入

l1 = [7,2,4,3], l2 = [5,6,4]

样例输出

[7,8,0,7]

提示

链表的长度范围为 [1, 100]
0 <= node.val <= 9
输入数据保证链表代表的数字无前导 0

c++代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        stack<int> s1, s2;
        while(l1){
            s1.push(l1->val);
            l1 = l1->next;
        }
        while(l2){
            s2.push(l2->val);
            l2 = l2->next;
        }
        int carry = 0;
        ListNode* head = nullptr, *tail = nullptr;
        while(!s1.empty() || !s2.empty() || carry){
            int n1 = s1.empty()? 0:s1.top();
            int n2 = s2.empty()? 0:s2.top();
            if(!s1.empty()) s1.pop();
            if(!s2.empty()) s2.pop();
            carry += n1 + n2;
            if(head == nullptr){
                tail = new ListNode(carry % 10);
                head = new ListNode(0);
                head->next = tail;
            }else{
                ListNode* temp = head->next;
                head->next = new ListNode(carry % 10);
                head->next->next = temp;
            }
            carry = carry / 10;
        }
        return head->next;
    }
};

python代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        s1,s2 = [], []
        while l1:
            s1.append(l1.val)
            l1 = l1.next
        while l2:
            s2.append(l2.val)
            l2 = l2.next
        head = tail = None
        carry = 0
        while s1 or s2 or carry:
            n1 = s1.pop() if s1 else 0
            n2 = s2.pop() if s2 else 0
            carry += n1 + n2
            if not head:
                tail = ListNode(carry % 10)
                head = ListNode(0)
                head.next = tail
            else:
                temp = head.next
                head.next = ListNode(carry % 10)
                head.next.next = temp
            carry = carry // 10
        return head.next

备注

利用好栈的特性,使用head和tail两个结点可以应付所有创建列表的需要。python中的栈可以使用列表来实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值