python - 两个链表的总和 python --CTCI 的问题
问题描述
我正在尝试运行下面的代码,我希望代码返回一个名为 head 的列表,其中包含 (first 和 second) 的总和,其中 first 和 second 是作为参数传递的链表。
正如你在最后看到的,我创建了两个链表l1
和l2
. 我假设这个链表将从Node
类继承。
但它给出了一个属性错误。我似乎无法弄清楚问题所在。我是编程新手,自学。什么可能导致此错误?我们如何着手解决它?
class Node:
def __init__(self,data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def display(self):
elems = []
current = self.head
while current != None:
elems.append(current.data)
current = current.next
return elems
def append(self, data):
elem = Node(data)
if self.head == None:
self.head = elem
else:
current = self.head
while current.next != None:
current = current.next
current.next = elem
def addTwoLists(self, first, second):
head = third = Node(0)
carry = 0
while first or second or carry:
if first:
carry += first.data
first = first.next
if second:
carry += second.data
second = second.next
third.data = carry % 10
carry = carry // 10
if first or second or carry:
third.next = Node(0)
third = third.next
return head
ll = LinkedList()
list1 = LinkedList()
list2 = LinkedList()
list1.append(7)
list1.append(1)
list1.append(6)
print(list1.display())
list2.append(5)
list2.append(9)
list2.append(2)
print(list2.display())
ll.addTwoLists(list1,list2)
print(ll.display())
我得到它的错误:
carry += first.data
AttributeError: 'LinkedList' object has no attribute 'data'
解决方案
您需要区分 aLinkedList
和 a Node
。
我假设这个链表将从
Node
类继承。
虽然他们有关系,但它不是继承。它们之间的唯一联系是LinkedList
包含 Node
s。通过执行以下操作在语法上实现继承:class LinkedList(Node):
,但这在您的情况下似乎在逻辑上不正确(LinkedList
不是a Node
,但它确实包含a Node
,就像您当前的代码一样)。
对变量使用有意义的名称可以帮助解决这种混淆。请注意,参数addTwoLists
是列表,但您将它们视为具有data
属性的节点。
您需要决定的另一件事是您的函数是返回一个新列表还是改变一个列表。我知道您想返回一个新方法,在这种情况下,该方法可以是静态的,也可以根本不在类中(因为您从未真正使用过self
)。目前,您的方法不会改变任何对象,您也不会使用它的返回值。
您可以在类之外定义它并使其返回一个新列表:
def addTwoLists(first_list, second_list):
third_list = LinkedList()
carry = 0
first_node = first_list.head
second_node = second_list.head
while first_node or second_node or carry:
if first_node:
carry += first_node.data
first_node = first_node.next
if second_node:
carry += second_node.data
second_node = second_node.next
third_list.append(carry % 10)
carry = carry // 10
return third_list
然后在您的主代码中,只需执行ll = addTwoLists(list1, list2)
推荐阅读
- algorithm - 基于顾客口味的推荐算法
- javascript - 使用扫描图像检测 html5 画布中是否存在图像或形状
- kotlin - 尝试使用 r2dbc 选择最大值导致 NullPointerException: data
- python - 使用 Python 打印图像
- adobe - 如何在 AEM 上创建新的资产元数据架构属性?
- ajax - 检查矩形和圆内的点
- android - 在 Android 12 DocumentFile toString() 中不会返回与以前版本相反的文本
- json - 从 ADF 到 SQL 存储过程的 Json 输入参数
- android-studio - 如何在主线程之外运行 afterTextChanged?
- javascript - 为什么 FieldSelect 返回一个字符串,而 FieldCheckbox 返回一个对象?