class prio_queue(object):
"""docstring for prio_queue,最小堆优先队列"""
def __init__(self, elems=[]):
self._elems = list(elems)
self.build_queue()
def clear_queue(self): #清除整个队列
self._elems=[]
def get_head(self): #获得队列的第一个元素,不改变队列
if self.is_empty():
raise SyntaxError("the queue is empty")
return self._elems[0]
def queue_length(self): #返回队列长度
return len(self._elems)
def is_empty(self): #返回队列是否为空
if self.queue_length()>0:
return False
else:
return True
def enqueue(self,e): #插入一个元素进队列
self._elems.append(None)
index = len(self._elems)-1
self._adjust_up(index,e)
def dequeue(self): #取出队列第一个元素,并从队列中删除它
if self.is_empty():
raise SyntaxError("the queue is empty")
e0 = self._elems[0]
self._elems[0]=self._elems[-1]
self._elems.pop()
self._adjust_down(0)
return e0
def build_queue(self): #构建最小堆
j = (len(self._elems)-2)//2
while j>=0:
self._adjust_down(j)
j-=1
def _adjust_down(self,index): #向下调整堆
i,j,length = index,2*index+1,len(self._elems)-1
while j<=length:
if j+1<=length and self._elems[j]>self._elems[j+1]:
j+=1
if self._elems[i] <= self._elems[j]:
break
else:
temp = self._elems[i]
self._elems[i]=self._elems[j]
self._elems[j] = temp
i=2*i+1
j = 2*i+1
def _adjust_up(self,index,e): #向上调整堆
i,j = index,(index-1)//2
while i>0 and e<self._elems[j]:
self._elems[i]=self._elems[j]
i,j=j,(i-1)//2
self._elems[i]=e
if __name__=='__main__': #测试用例
queue = prio_queue([6,2,8,3,5,1,7,4])
print(queue.get_head())
print(queue.queue_length())
print(queue.is_empty())
queue.enqueue(4)
queue.enqueue(17)
queue.enqueue(-1)
print(queue.dequeue())
print(queue.dequeue())
queue.clear_queue()
print(queue.queue_length())
print(queue.is_empty())
print(queue.get_head())