# 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: ListNode, l2: ListNode) -> ListNode:
head = None
tail = None
carry = 0
while l1 or l2:
if l1:
n1 = l1.val
else:
# 补0操作
n1 = 0
if l2:
n2 = l2.val
else:
n2 = 0
sumData = n1 + n2 + carry
if head:
# head不为空
tail.next = ListNode(sumData%10)
tail = tail.next
else:
# head为空
head = tail = ListNode(sumData%10)
carry = sumData // 10
# 往后滑指针
if l1:
l1 = l1.next
if l2:
l2 = l2.next
if carry > 0:
# 需要在tail后再加一个carry
tail.next = ListNode(carry)
return head
每日一道Leetcode - 2. 两数相加 【链表两数相加】
最新推荐文章于 2023-10-27 19:05:47 发布