我知道在将实例方法或任何预设函数插入到None
类型时会发生这些错误,但由于我正在实现单链表,我需要为最后一个节点分配None
类型。我如何解决这个问题,因为我无法更改此处的输入值。
以下是我的代码——
class singlyLinked:
class _node:
def __init__(self, data, next):
self._data = data
self._next = next
def __init__(self):
self._head=None
self._tail=None
self._size=0
def __len__(self):
return self._size
def isEmpty(self):
return self._size==0
def first(self):
if self.isEmpty():
raise Error('Queue is Empty')
return self._head._data #front aligned with the head of list
def dequeue(self):
if self.isEmpty():
raise Error('Queue is Empty')
answer=self._head._data
self._head=self._head._next
self._size -= 1
if self.isEmpty():
self._tail=None
return answer
def enqueue(self, e):
newest=self._node(e, None)
if self.isEmpty():
self._head=newest
else:
self._tail._next=newest
self.tail=newest
self._size+=1
我在Jupyter笔记本中得到以下错误
AttributeError Traceback (most recent call last)
Cell In [20], line 3
1 a=singlyLinked()
2 a.enqueue(5)
----> 3 a.enqueue(5)
4 a.enqueue(5)
5 a.enqueue(5)
Cell In [19], line 41, in singlyLinked.enqueue(self, e)
39 self._head=newest
40 else:
---> 41 self._tail._next=newest
42 self.tail=newest
43 self._size+=1
AttributeError: 'NoneType' object has no attribute '_next'
您可以将入队函数更改为:
def enqueue(self, e):
newest=self._node(e, None)
if self.isEmpty():
self._head=newest
self._tail=newest
else:
self._tail._next=newest
self._tail=newest
self._size+=1
中有一个打字错误
newest=self._node(e, None)
if self.isEmpty():
self._head=newest
else:
self._tail._next=newest
self.tail=newest
self._size+=1
您需要:
self._tail = newest
(带下划线(