Python Leetcode在列表节点中添加两个sum';未定义错误
2#@返回一个ListNode 3个def addtwo编号(self、l1、l2): ---->4虚拟=cur=列表节点(0) 5进位=0 6当l1或l2或运载时:Python Leetcode在列表节点中添加两个sum';未定义错误,python,Python,2#@返回一个ListNode 3个def addtwo编号(self、l1、l2): ---->4虚拟=cur=列表节点(0) 5进位=0 6当l1或l2或运载时: NameError:名称“ListNode”未定义ListNode应由LeetCode定义,ListNode由LeetCode定义的Playerd按钮中有调试代码最初在编辑器面板中提供,如Python2所示: class Solution: # @return a ListNode def addTwoNumbers(se
NameError:名称“ListNode”未定义ListNode应由LeetCode定义,ListNode由LeetCode定义的Playerd按钮中有调试代码最初在编辑器面板中提供,如Python2所示:
class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
dummy = cur = ListNode(0)
carry = 0
while l1 or l2 or carry:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
cur.next = ListNode(carry%10)
cur = cur.next
carry //= 10
return dummy.next
l1 = [203] # Array of numbers
l2 = [433]
s = Solution()
print(s.addTwoNumbers(l1, l2))
下面是在Python中使用while循环的完整解决方案,但是,使用递归调用要好得多:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
嗯,您还没有在任何地方定义
ListNode
类,所以。。。为什么您希望这段代码能工作?您能编写ListNode类吗?对于那些不使用Leetcode的人来说,它会派上用场。我的答案中提供了ListNode。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2, carry = 0):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# Initialize the tmp result and the returned result
head_result = tmp_result = ListNode(0)
# While loop until there are neither nodes or carries left
while l1 != None or l2 != None or carry > 0:
# Store the values of the linked lists into variables, and set zero if no more nodes
x = (l1.val if l1 != None else 0)
y = (l2.val if l2 != None else 0)
# Calculate the sum
sum_res = x + y + carry
# Make the tens of the sum be the carry
carry = sum_res // 10
# Store the units of the sum in the result's next node
tmp_result.next = ListNode(sum_res % 10)
# Traverse to the next result's node
tmp_result = tmp_result.next
# Traverse to the next nodes in the linked lists
l1 = (l1.next if l1 else None)
l2 = (l2.next if l2 else None)
# Make sure no carries are left
if carry > 0: tmp_result.next = ListNode(carry)
# Set the head of the result to skip the zero intialization, if there's something in the next node
if head_result.next != None: head_result = head_result.next
return head_result