【发布时间】:2021-10-10 06:37:42
【问题描述】:
以下是我的代码,它尝试将两个数字相加,这两个数字也以相反的顺序存储在链表中,并将总和作为链表返回。
但是当我尝试在 LeetCode 中运行这段代码时,它指出这超出了时间。我认为它可能会卡在 while 循环中?
提前感谢您的帮助。我对 Python 非常陌生,很抱歉这个愚蠢的问题。
# 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
"""
result = ListNode()
carry = 0
while l1 != None or l2 != None or carry:
if l1 == None:
v1 = 0
else:
v1 = l1.val
if l2 == None:
v2 = 0
else:
v2 = l2.val
total = v1 + v2 + carry
carry = total // 10
total = total % 10
result.next = ListNode(total)
if l1 != None:
l1.next
if l2 != None:
l2.next
return result
【问题讨论】:
标签: python python-3.x data-structures