当前位置:网站首页>剑指 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
边栏推荐
- Process control and method
- Common APIs and exception mechanisms
- 【機器學習】基於多元時間序列對高考預測分析案例
- [proficient in high concurrency] deeply understand the basis of C language and C language under assembly
- 剑指 Offer 39. 数组中出现次数超过一半的数字
- Day_ fourteen
- Difference between app test and web test
- 【无标题】
- Optimization of lazyagg query rewriting in parsing data warehouse
- What is backbone network
猜你喜欢

Wireshark network card cannot be found or does not display the problem

六大专题全方位优化,阿里巴巴性能优化小册终开源,带你直抵性能极致

How did I get a salary increase of 13k+ after one year of employment?

Reading mysql45 lecture - index continued

完美洗牌问题

从TiDB上线阿里云的背后,如何看待云数据库的变革趋势

PLSQL 存储函数SQL编程

The first day of reading mysql45
![[100 questions of Blue Bridge Cup intensive training] scratch command mobile Blue Bridge Cup scratch competition special prediction programming question intensive training simulation exercise question](/img/45/9955c9a5edeaa681f3fa8ce4041bfe.png)
[100 questions of Blue Bridge Cup intensive training] scratch command mobile Blue Bridge Cup scratch competition special prediction programming question intensive training simulation exercise question

SDN系统方法 | 10. SDN的未来
随机推荐
Hash table, generic
How to talk about salary correctly in software testing interview
批量--07---断点重提
根据先序遍历和中序遍历生成后序遍历
Kalman filter meets deep learning: papers on Kalman filter and deep learning
Redis series - overview day1-1
八种button的hover效果
【精通高并发】深入理解汇编语言基础
Ad domain login authentication
Android修行手册之Kotlin - 自定义View的几种写法
Optimization of lazyagg query rewriting in parsing data warehouse
解析数仓lazyagg查询重写优化
Redis Series - Overview day1 - 1
Day21 multithreading
Day_ 18 hash table, generic
【精通高并发】深入理解C语言基础与汇编下的C语言
【无标题】
How did I raise my salary to 20k in three years?
Unity技术手册 - 生命周期内大小(Size over Lifetime)和速度决定大小(Size by Speed)
Redis系列——概述day1-1