当前位置:网站首页>剑指 Offer II 025. 链表中的两数相加
剑指 Offer II 025. 链表中的两数相加
2022-06-25 16:35:00 【Python ml】
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*res=nullptr;
while(!s1.empty() or !s2.empty() or carry!=0){
int a=s1.empty()?0:s1.top();
int b=s2.empty()?0:s2.top();
if(!s1.empty()) s1.pop();
if(!s2.empty()) s2.pop();
int cur=a+b+carry;
carry=cur/10;
cur%=10;
ListNode*curnode=new ListNode(cur);
curnode->next=res;
res=curnode;
}
return res;
}
};
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
s1, s2 = [], []
while l1:
s1.append(l1.val)
l1 = l1.next
while l2:
s2.append(l2.val)
l2 = l2.next
ans = None
carry = 0
while s1 or s2 or carry != 0:
a = 0 if not s1 else s1.pop()
b = 0 if not s2 else s2.pop()
cur = a + b + carry
carry = cur // 10
cur %= 10
curnode = ListNode(cur)
curnode.next = ans
ans = curnode
return ans
边栏推荐
- Are these old system codes written by pigs?
- 万卷书 - 大力娃的书单
- 一个 TDD 示例
- Redis series - overview day1-1
- Day_ 18 hash table, generic
- 剑指 Offer 50. 第一个只出现一次的字符
- Mysql database multi table query
- 论文笔记:LBCF: A Large-Scale Budget-Constrained Causal Forest Algorithm
- [proficient in high concurrency] deeply understand the basis of C language and C language under assembly
- 八种button的hover效果
猜你喜欢
随机推荐
Redis series - overview day1-1
Do you know all the configurations of pychrm?
Perfect shuffle problem
Bypass technology to talk about 'cross end'
Day_ fourteen
ncnn源码学习全集
【无标题】
Simple dialogue system -- implement transformer by yourself
【效率】又一款笔记神器开源了!
Differences between et al and etc
万卷书 - 大力娃的书单
Wechat official account server configuration
Problems encountered in using MySQL
JVM内存结构
Paper notes: generalized random forests
What is backbone network
Read mysql45 - a simple understanding of global locks and table locks
2022-06-17 advanced network engineering (IX) is-is- principle, NSAP, net, area division, network type, and overhead value
Ncnn source code learning collection
DDD概念复杂难懂,实际落地如何设计代码实现模型?









