首页 > 解决方案 > “节点”对象没有属性“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

预期的输出是新节点应该是新的头节点。

标签: pythonpython-3.xlinked-listsingly-linked-list

解决方案


这将修复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

推荐阅读