添加链接描述
# 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: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:head=mylist=ListNode()v=0while l1 or l2 or v:v=(l1.val if l1 else 0)+(l2.val if l2 else 0)+vmylist.next=ListNode(v%10)v=v//10mylist=mylist.nextl1=l1.next if l1 else Nonel2=l2.next if l2 else Nonereturn head.next
思路:
- 最后判断l1和l2是否为空的时候,这个if else很好用,不会出现none.nexr
- 还有在判断l1是否有值的时候,使用的if else判断