可惜没如果=_=
时光的河入海流

题目链接在这里:2. 两数相加 - 力扣(LeetCode)

这道题学了一些python类和子函数的语法,发现语法与C++有异曲同工之妙

 1 class ListNode:
 2     def __init__(self, val=0, next=None) -> None:
 3         self.val = val
 4         self.next = next
 5 
 6 class Solution:
 7     def addTwoNumbers(self, l1:ListNode, l2:ListNode) -> ListNode:
 8         head = tree = ListNode()
 9         val = tmp = 0
10         while tmp or l1 or l2:
11             val=tmp
12             if (l1):
13                 val+=l1.val
14                 l1=l1.next
15             if (l2):
16                 val+=l2.val
17                 l2=l2.next
18             tmp = val // 10
19             val%=10
20             tree.next = ListNode(val)
21             tree=tree.next
22         return head.next

 

posted on 2023-03-13 17:52  珍珠鸟  阅读(16)  评论(0编辑  收藏  举报