属性错误:“LinkedList”对象没有属性“insert_head”

问题描述 投票:0回答:1

我尝试将元素插入到单个链表的 head 中 我不明白我的代码有什么问题。它说:

AttributeError: 'LinkedList' object has no attribute 'insert_head'

这是我的代码:

class LinkedList:
    def _init_(self):
        # Empty LinkedList
        self.head = None
        # no of nodes in the LinkedList
        self.n = 0

class Node:
    def __init__(self,value):
        self.data = value
        self.next = None

    def _len_(self):
        return self.n
    
    def insert_head(self,value):
        #new node
        new_Node = Node(value)

        #Create onnection
        new_Node.next = self.head

        #Reasign head
        self.head = new_Node

        #Increment n
        self.n = self.n + 1

L = LinkedList()

L.insert_head(1)

len(L)

输出应该是5

python-3.x singly-linked-list insertion
1个回答
0
投票

原因很明显,

LinkedList
没有
insert_head
方法。它在
Node
类中定义。

事实上

Node
对象应该是数据的容器和对下一个节点的引用,仅此而已。例如,他们不应该知道链表的长度。

您应该将代码重构为如下所示:

class Node:
    def __init__(self, value):
        self.data = value
        self.next = None


class LinkedList:
    def __init__(self):
        self.head = None
        self.n = 0

    def __len__(self):
        return self.n

    def insert_head(self, value):
        new_Node = Node(value)

        # Create onnection
        new_Node.next = self.head

        # Reasign head
        self.head = new_Node

        # Increment n
        self.n = self.n + 1


l = LinkedList()
l.insert_head(20)
print(len(l))
© www.soinside.com 2019 - 2024. All rights reserved.