题目介绍:
解法一(普通解法):
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = point = ListNode(0) # 创建头结点和指针point(初始指向head)
carry = 0 # 设置进位
while l1 or l2:
new_point = ListNode(0)
if not l1: # l1为空时,只计算l2
carry,new_point.val = divmod(l2.val+carry,10)
l2 = l2.next
elif not l2: # l2为空时,只计算l1
carry,new_point.val = divmod(l1.val+carry,10)
l1 = l1.next
else: # l1 , l2 都不为空时, 同时计算l1,l2
carry,new_point.val = divmod(l1.val+l2.val+carry,10) # divmod是python的内置函数,把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)
l1 = l1.next
l2 = l2.next
point.next = new_point
point = point.next
if carry:
new_point = ListNode(1)
point.next = new_point
return head.next
解法二(简化了一丢丢):
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = point = ListNode(0)
carry = 0
while l1 or l2 :
new_point = ListNode(0)
if l1:
new_point.val += l1.val
l1 = l1.next
if l2:
new_point.val += l2.val
l2 = l2.next
carry, new_point.val = divmod(new_point.val + carry, 10)
point.next = new_point
point = point.next
if carry:
new_point = ListNode(1)
point.next = new_point
# point = point.next #此时程序结束,没有必要再更新 point 的位置了
return head.next
补充:
- .在实际调试中,需要自己写函数将列表转化为ListNode,可以参考这里;但是需要注意的是力扣有自己的ListNode 的格式,实际提交时需注意