python3
算法思路参考: 画解算法-两数相加
#
# @lc app=leetcode.cn id=2 lang=python3
#
# [2] 两数相加
#
# @lc code=start
# 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:
#不是列表,是链表
# sum = x + y + carry
pre = ListNode(0) #预先指针
r = pre
carry = 0 #进位
while (l1 or l2) :
x = l1.val if l1 else 0
y = l2.val if l2 else 0
sum = x + y + carry
carry = sum // 10
sum = sum - 10 * carry
r.next = ListNode(sum)
r = r.next
if(l1!=None):l1=l1.next
if(l2!=None):l2=l2.next
#如果进位carry为1
if(1==carry):
r.next=ListNode(1)
return pre.next
# @lc code=end