问题
解答
满十进一的初等数学问题,设定一个哑节点dummyHead
便于返回最终结果,d
=dummyHead
,d用于按序储存结果,从左加到右满十进位carry
要么是1要么是0。最终求和结束后,如果carry大于0就在链表中再添加一个值为1的节点
时间复杂度:O(max(m,n))
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
dummyHead= ListNode(-1)
d=dummyHead
carry=0
while(l1 or l2):
x= l1.val if l1 else 0
y= l2.val if l2 else 0
sum=carry+x+y
carry=sum//10 #整数除法
d.next=ListNode(sum%10)
d=d.next
if(l1!=None):
l1=l1.next
if(l2!=None):
l2=l2.next
if(carry>0):
d.next=ListNode(1)
return dummyHead.next