python - “节点”对象没有属性“set_next”
问题描述
当我插入一个新节点时,我得到 AttributeError:'Node' 对象没有属性'set_next'。我真的不明白为什么,因为在我的 Node 类中我有一个方法 set_next。那不是我打电话的那个吗?
class Node(object):
def __init__(self, val):
self.val = val
self.next = None
def get_data(self):
return self.val
def set_data(self, val):
self.val = val
def get_next(self):
return self.next
def set_next(self, next):
self.next = next
class LinkedList(object):
def __init__(self, head=None):
self.head = head
self.count = 0
def get_count(self):
return self.count
def insert(self, data):
new_node = Node(data)
new_node.set_next()
self.head = new_node
self.count += 1
预期的输出是新节点应该是新的头节点。
解决方案
这将修复AttributeError
和后续的TypeError
.
class Node(object):
def __init__(self, val):
self.val = val
self.next = None
# fixed indentation here
def get_data(self):
return self.val
def set_data(self, val):
self.val = val
def get_next(self):
return self.next
def set_next(self, next):
self.next = next
class LinkedList(object):
def __init__(self, head=None):
self.head = head
self.count = 0
def get_count(self):
return self.count
def insert(self, data):
new_node = Node(data)
# fix logic here
new_node.set_next(self.head)
self.head = new_node
self.count += 1
测试
linked_list = LinkedList()
linked_list.insert('hello')
linked_list.insert('world')
print(linked_list.count)
print(linked_list.head.val)
print(linked_list.head.next.val)
输出
2
world
hello
请注意,如您所见,此 LinkedList 仅在列表的前面插入,而不是在末尾。
奖金
如果要遍历列表,请使用此方法
def __iter__(self):
node = self.head
while node is not None:
yield node.val
node = node.next
推荐阅读
- firebase - 如何将 Firebase 远程配置值获取到 firebase 函数中
- sql - 就联接而言,在 sql 查询中添加包含项的正确方法是什么?
- python - 在实现权限时,如何让 Django 重定向到另一个页面而不是登录?
- java - 我如何解决这个错误:控制台无法读取数据
- shell - 获取命令“mv -n”linux的返回值
- java - 为什么不鼓励在 Java 程序中使用全局变量?
- apache-spark - 将 spark2 依赖项、avro 数据块添加到 zeppelin 0.7.3 时出错
- c# - 如何将 RS256 算法与 RSACryptoServiceProvider 一起使用
- mongodb - 从 Kubernetes 中的另一个服务访问服务
- google-sheets - 自动清除单元格