# 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:
s1=[]
s2=[]
#放入栈中
while l1:
s1.append(l1.val)
l1=l1.next
while l2:
s2.append(l2.val)
l2=l2.next
#print(s1,s2)
carry=0
ans=None
while s1 or s2 or carry !=0:
#取每一位数相加
a1=0 if not s1 else s1.pop()
a2=0 if not s2 else s2.pop()
sum=a1+a2+carry
#取十位
carry=sum//10
#取个位
cur=sum%10
#建立结果链表
curnode=ListNode(cur)
curnode.next=ans
ans=curnode
return ans
代码分析
1、基本思路就是取出来相加
2、涉及进位,应该从低位开始,使用栈来装取出的值,刚好是先进后出
3、整除//
获得十位,余数%
取得个位,十位在下一次循环进行相加,个位存入链表
4、反向建立链表:
ans = None
{#循环
curnode = ListNode(cur) #建立新节点
curnode.next = ans #指向现有的链表的head
ans = curnode #head 向前移
}
python语法
print("*******if not...else语句*********")
#if not 为假返回if not前面内容,否则返回0
exp3 = lambda x:x+1 if not 2==1 else 0
print(exp3(2))
exp4 = lambda x:x+1 if not 1==1 else 0
print(exp4(2))
结果:
3
0
[Finished in 0.3s]
错误:
不能直接赋值,否则获得节点,需用l1.val
和append