1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 #Author: Minion-Xu 5 #list实现优先队列 6 7 class ListPriQueueValueError(ValueError): 8 pass 9 10 class List_Pri_Queue(object):11 def __init__(self, elems = []):12 self._elems = list(elems)13 #从大到小排序,末尾值最小,但优先级最高,方便弹出且效率为O(1)14 self._elems.sort(reverse=True)15 16 #判断队列是否为空17 def is_empty(self):18 return self._elems is []19 20 #查看最高优先级 O(1)21 def peek(self):22 if self.is_empty():23 raise ListPriQueueValueError("in pop")24 return self._elems[-1]25 26 #弹出最高优先级 O(1)27 def dequeue(self):28 if self.is_empty():29 raise ListPriQueueValueError("in pop")30 return self._elems.pop()31 32 #入队新的优先级 O(n)33 def enqueue(self, e):34 i = len(self._elems) - 135 while i>=0:36 if self._elems[i] < e:37 i -= 138 else:39 break40 self._elems.insert(i+1, e)41 42 if __name__=="__main__":43 l = List_Pri_Queue([4,6,1,3,9,7,2,8])44 print(l._elems)45 print(l.peek())46 l.dequeue()47 print(l._elems)48 l.enqueue(5)49 print(l._elems)50 l.enqueue(1)51 print(l._elems)