# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = cur = ListNode(0) #链表节点头,方便后续操作
carry = 0
while l1 or l2 or carry: #l1,l2,carry不都为0的时候进行循环操作
if l1:
carry += l1.val #carry加上l1的值
l1 = l1.next #l1挪动到下一位
if l2:
carry += l2.val #类似累加
l2 = l2.next
cur.next = ListNode(carry%10) #取余
cur = cur.next #挪动节点
carry //= 10 # carry = carry//10
return dummy.next
python;leetcode 两数相加
最新推荐文章于 2024-01-18 09:40:46 发布