您的位置:首页 > 其它

LeetCode每日一题——T2. 两数相加(中):链表

2019-06-25 19:58 387 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/qq_41514090/article/details/93649074


要点:链表用法、添加链表节点、地板除法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
carry = 0
out =  p = ListNode(0)
while l1 is not None and l2 is not None:
temp = l1.val + l2.val + carry
l1 = l1.next
l2 = l2.next
p.next = ListNode(temp % 10)
carry = temp // 10	'''注意要用地板除法'''
p = p.next

while l1 is not None:
temp = l1.val + carry
l1 = l1.next
p.next = ListNode(temp % 10)
carry = temp // 10	'''注意要用地板除法'''
p = p.next

while l2 is not None:
temp = l2.val + carry
l2 = l2.next
p.next = ListNode(temp % 10)
carry = temp // 10	'''注意要用地板除法'''
p = p.next
if carry:
p.next = ListNode(1)
out = out.next
return out
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: