题解 1:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0 # 初始化进位为0
dummy_head = ListNode(0) # 创建一个虚拟头结点
current = dummy_head # 初始化当前节点指向虚拟头结点
while l1 or l2:
x = l1.val if l1 else 0 # 获取l1当前节点的值,如果l1已经遍历完,则为0
y = l2.val if l2 else 0 # 获取l2当前节点的值,如果l2已经遍历完,则为0
# 计算当前位的和,加上进位
_sum = x + y + carry
carry = _sum // 10 # 更新进位
current.next = ListNode(_sum % 10) # 创建新节点,存储当前位的和
current = current.next # 移动current指针
if l1:
l1 = l1.next
if l2:
l2 = l2.next
# 处理最高位可能的进位
if carry > 0:
current.next = ListNode(carry)
return dummy_head.next # 返回结果链表的头节点
class Solution(object):
def addTwoNumbers(self, l1, l2):
carry = 0 # 初始化进位为0
dummy_head = ListNode() # 创建一个虚拟头结点,无需默认值
current = dummy_head # 初始化当前节点指向虚拟头结点
while l1 or l2 or carry:
# 获取l1和l2当前节点的值,如果l1或l2已经遍历完,则为0
x = l1.val if l1 else 0
y = l2.val if l2 else 0
# 计算当前位的和,加上进位
_sum = x + y + carry
# 计算新的进位值和当前位的结果
carry, result = divmod(_sum, 10)
# 创建新节点,存储当前位的结果
current.next = ListNode(result)
# 移动current指针到新的节点
current = current.next
# 移动到下一个节点,如果l1或l2不为空的话
if l1:
l1 = l1.next
if l2:
l2 = l2.next
return dummy_head.next # 返回结果链表的头节点