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
對不起,我的壞。謝謝,我剛剛添加它。 –