力扣题库2
关键词:
模拟数学过程
解法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
l1temp = l1
l2temp = l2
length1 = 0
length2 = 0
gw = 0
sw = 0
add = 0
out=[]
result = ListNode()
resulttemp = result
while(True):
length1 = length1 + 1
l1temp = l1temp.next
if(l1temp==None):
break
while(True):
length2 = length2 + 1
l2temp = l2temp.next
if(l2temp==None):
break
for i in range(min(length1,length2)):
add = l1.val+l2.val+sw
gw = add%10
sw = add//10
resulttemp.val = gw
resulttemp.next = ListNode()
l1 = l1.next
l2 = l2.next
resulttemp = resulttemp.next
if(l1!=None):
while(l1!=None):
add = sw + l1.val
gw = add%10
sw = add//10
resulttemp.val = gw
resulttemp.next = ListNode()
l1 = l1.next
resulttemp = resulttemp.next
resulttemp.val = sw
else:
while(l2!=None):
add = sw + l2.val
gw = add%10
sw = add//10
print("gw",gw)
print("sw",sw)
resulttemp.val = gw
resulttemp.next = ListNode()
l2 = l2.next
resulttemp = resulttemp.next
resulttemp.val = sw
out = result
last = 0
selast = result
while(result!=None):
last = result.val
result = result.next
while(selast.next.next!=None):
selast = selast.next
if(last==0):
selast.next=None
return out