class Node:
def __init__(self, data=None, priority='L', next=None):
self.data = data
self.priority = priority
self.next = next
def __str__(self):
return str(self.data)
class P_Queue:
def __init__(self, head=None):
self.head = head
self.length = 0
def enqueue(self, node):
newNode = Node(node.data, node.priority)
if (self.head == None):
self.head = newNode
elif (self.head and self.head.priority == 'L' and newNode.priority == 'H'):
newNode.next = self.head
self.head = newNode
elif (self.head and self.head.priority == 'H' and newNode.priority == 'H'):
last = self.head
while (last.next and last.next.priority == 'H'):
last = last.next
if (last.next and last.next.next):
newNode.next = last.next.next
last.next = newNode
else:
last = self.head
while last.next:
last = last.next
last.next = newNode
self.length += 1
def dequeue(self):
node = self.head
print("next head: ")
print(self.head.next)
self.head = self.head.next
self.length = self.length - 1
return node
def is_empty(self):
return self.length==0
def main():
node0 = Node(0, 'L')
node1 = Node(1, 'H')
node2 = Node(2, 'H')
queue = P_Queue()
queue.enqueue(node0)
queue.enqueue(node1)
queue.enqueue(node2)
print(queue.dequeue())
print(queue.dequeue())
print(queue.dequeue())
main()
所显示的代码在队列()while语句,我得到错误“的最后一行出现该问题的‘无类型’的对象有没有属性属性(但是,根据我的print0语句(output:H)node0 = Node(0,'H'),我清楚地知道该属性的值为'H' (优先级),它不包含'None'值,所以对我来说只是令人难以置信的。的Python:带有链接节点
请帮助...如果有人有一个很好的资源,学习如何实现优先队列与链接列表的初学者,这将是伟大的。非常感谢你,我在这里死去。
下面回溯:
next head: 2
1
next head: None
2
next head:
Traceback (most recent call last):
File "assignment1_3 queues.py", line 62, in <module>
main()
File "assignment1_3 queues.py", line 60, in main
print(queue.dequeue())
File "assignment1_3 queues.py", line 39, in dequeue
print(self.head.next)
AttributeError: 'NoneType' object has no attribute 'next'
------------------
(program exited with code: 1)
Press any key to continue . . .
你能追溯添加到您的问题吗? – Vinny
对不起,我的坏。谢谢,我刚刚添加它。 –