from myNode import *
from tasks import *
class PriorityQueue():
__slots__ = ( 'front', 'back', 'size' )
def mkPriorityQueue():
queue = PriorityQueue()
queue.front = NONE_NODE
queue.back = NONE_NODE
queue.size = 0
return queue
def insert(queue, element):
newnode = mkNode(element, NONE_NODE)
if emptyQueue(queue):
#if the queue was empty, the new node is now both the first and last one
queue.front = newnode
queue.back = newnode
elif frontMax(queue).priority > newnode.data.priority:
#if the new node has a higher priority than the first, insert at front
newnode.next = queue.front #old first is now second node
queue.front = newnode
else:
#the node has a lower priority than the first
#find the next node with a lower priority, insert newnode before that
currentnode = queue.front
while not currentnode.next == NONE_NODE:
#traverse nodes until we find a lower priority or until the end
if currentnode.next.data.priority < newnode.data.priority:
break
currentnode = currentnode.next
#insert newnode between currentnode and currentnode.next
newnode.next = currentnode.next
currentnode.next = newnode
#if newnode.next is now NODE_NONE, we're at the end so change backMin
if newnode.next == NONE_NODE:
queue.back = newnode
queue.size += 1
def removeMax(queue):
"""Remove the front element from the queue (returns None)"""
if emptyQueue(queue):
raise IndexError("Cannot dequeue an empty queue")
queue.front = queue.front.next
if emptyQueue(queue):
queue.back = NONE_NODE
queue.size -= 1
def frontMax(queue):
"""Access and return the first element in the queue without removing it"""
if emptyQueue(queue):
raise IndexError("front on empty queue")
return queue.front.data
def backMin(queue):
"""Access and return the last element in the queue without removing it"""
if emptyQueue(queue):
raise IndexError("back on empty queue")
return queue.back.data
def emptyQueue(queue):
"""Is the queue empty?"""
return queue.front == NONE_NODE
我这样做对吗?以下是我要解决的问题。我已经添加了我所做的所有功能。
使用优先级规则插入(在插入函数下)(每个任务具有从 10(最高优先级)到 1(最低优先级)的整数优先级。如果两个任务具有相同的优先级,则顺序应基于它们的顺序插入优先级队列(较早的第一个)。