Add Two Numbers ,使用链表参数
2024-10-16 16:39:32
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None class Solution(object):
def addTwoNumbers(self, l1, l2):
l3 = ListNode()
current = l3
carry =
while l1 or l2: # , | None, | ,None
# Pad if None
if l1 is None:
l1v =
else:
l1v = l1.val
if l2 is None:
l2v =
else:
l2v = l2.val
# Sum
tmp = l1v + l2v + carry
if tmp >= :
x = tmp%
carry = int(tmp/)
else:
x = tmp
carry =
# Assign value
current.next = ListNode(x)
current = current.next
if l1 is not None:
l1 = l1.next
if l2 is not None:
l2 = l2.next
if carry != :
current.next = ListNode(carry)
return l3.next node1=ListNode()
node2=ListNode()
node3=ListNode() node1.next=node2
node2.next=node3 node4=ListNode()
node5=ListNode()
node6=ListNode() node4.next=node5
node5.next=node6 x=Solution()
print(x.addTwoNumbers(node1,node4).val)
print(x.addTwoNumbers(node1,node4).next.val)
print(x.addTwoNumbers(node1,node4).next.next.val)
输出
最新文章
- 菜鸟git学习
- ES6 语法笔记
- XAF How to show custom forms and controls in XAF (Example)
- ModelAttribute注解
- Oracle中Long类型的使用与不可使用
- KB006: CSS 框模型( Box module )
- MongDB开启权限认证
- Docker学习笔记 - Docker容器的网络基础
- Kubernetes的十大使用技巧
- Android系统应用Mms之短信会话列表加载流程一
- T-SQL:qualify和window 使用(十七)
- 【小技巧】css文字两端对齐
- linux下在root用户登陆状态下,以指定用户运行脚本程序实现方式
- codeforces 508B
- Angular4 Ng 模块
- 乘风破浪:LeetCode真题_035_Search Insert Position
- Shark简介、部署及编译小结
- Django在Win7下安装与创建项目hello word示例
- Extjs4.x treepanel,treegrid 节点选择,选中某个节点
- http-server 基于nodejs的http服务器
热门文章
- <;转>;jmeter(一)基础介绍
- Step5:SQL Server 跨网段(跨机房)FTP复制
- How to solve the problem that BMW Icom A2 A3 host can’t be connected?
- 常用的node.js模块
- 柳暗花明又一村的———for循环
- 如何解决win10关机状态下,按键盘会自动开机的问题
- How many zero&#39;s and how many digits ? UVA - 10061
- pat 团体赛练习题集 L2-006. 树的遍历
- Opencv改变图像亮度和对比度以及优化
- P2617 Dynamic Rankings(树状数组套主席树)