python中使用单链表实现队列的AttributeError
AttributeError in the implementation of queue by using Single Linked List in the python
我想用单链表实现一个队列。当我 运行 下面的代码时,我收到了 AttributeError。我不知道该怎么做才能解决这个问题。
我假设链表的第一个作为队列的前面,而那个作为队列的后面。
通过使用 while 循环,我想连接整个单链表。
class Node:
def __init__(self, value):
self.info = value
self.link = None
class Queue:
def __init__(self):
self.front = None
def enqueue(self, data):
temp = Node(data)
p = self.front
if self.front is None:
self.front = temp
while p.link is not None:
p = p.link
p.link = temp
temp.link = None
def dequeue(self):
self.front = self.front.link
def size(self):
p = self.start
n = 0
while p is not None:
p = p.link
n += 1
return n
def display(self):
p = self.start
while p is not None:
p = p.link
print(p.info, '', end='')
qu = Queue()
for i in range(4):
add = int(input("please enter the elements "))
qu.enqueue(add)
qu.display()
for i in range(2):
qu.dequeue()
qu.display()
Traceback (most recent call last):
File "C:/Users/HP/Music/Queue_SLList.py", line 43, in <module>
qu.enqueue(add)
File "C:/Users/HP/Music/Queue_SLList.py", line 18, in enqueue
while p.link is not None:
AttributeError: 'NoneType' object has no attribute 'link'
当队列为空时,您在 p = self.front
时将 p
设置为 None
。然后当您尝试执行 while p.link is not None
时会出现错误,因为 p
不是节点。
如果您要对第一个 noe 进行排队,您应该 return 从该方法中。
def enqueue(self, data):
temp = Node(data)
if self.front is None:
self.front = temp
return
p = self.front
while p.link is not None:
p = p.link
p.link = temp
temp.link = None
我想用单链表实现一个队列。当我 运行 下面的代码时,我收到了 AttributeError。我不知道该怎么做才能解决这个问题。 我假设链表的第一个作为队列的前面,而那个作为队列的后面。 通过使用 while 循环,我想连接整个单链表。
class Node:
def __init__(self, value):
self.info = value
self.link = None
class Queue:
def __init__(self):
self.front = None
def enqueue(self, data):
temp = Node(data)
p = self.front
if self.front is None:
self.front = temp
while p.link is not None:
p = p.link
p.link = temp
temp.link = None
def dequeue(self):
self.front = self.front.link
def size(self):
p = self.start
n = 0
while p is not None:
p = p.link
n += 1
return n
def display(self):
p = self.start
while p is not None:
p = p.link
print(p.info, '', end='')
qu = Queue()
for i in range(4):
add = int(input("please enter the elements "))
qu.enqueue(add)
qu.display()
for i in range(2):
qu.dequeue()
qu.display()
Traceback (most recent call last):
File "C:/Users/HP/Music/Queue_SLList.py", line 43, in <module>
qu.enqueue(add)
File "C:/Users/HP/Music/Queue_SLList.py", line 18, in enqueue
while p.link is not None:
AttributeError: 'NoneType' object has no attribute 'link'
当队列为空时,您在 p = self.front
时将 p
设置为 None
。然后当您尝试执行 while p.link is not None
时会出现错误,因为 p
不是节点。
如果您要对第一个 noe 进行排队,您应该 return 从该方法中。
def enqueue(self, data):
temp = Node(data)
if self.front is None:
self.front = temp
return
p = self.front
while p.link is not None:
p = p.link
p.link = temp
temp.link = None