基于python实现顺序存储的队列代码
""" 队列-顺序存储 seqqueue.py 代码实现 """ # 自定义异常类 class QueueError(Exception): pass # 队列-顺序存储代码-入队,出队,判断空满 class SeqQueue: def __init__(self): # 创建空列表作为存储空间 self._elems = [] # 入队-加到最后,内存不移动 def enqueue(self,val): self._elems.append(val) # 出队-头部删除,内存移动 def dequeue(self): # 空队列,报异常 # if not self._elems: # 如果为空,假假真 if self._elems == []: raise QueueError("queue is empty") # 非空队列,pop出第一个元素 return self._elems.pop(0) # 判断空满 def is_empty(self): return self._elems == [] # 打印队列 def print_queue(self): # 先判断是否为空 if self._elems == []: raise QueueError("queue is empty") else: for item in self._elems: print(item,end= " ") print() # 反转队列 或者用顺序栈的进出栈(出队入栈,出栈入队)方法 def reverse_queue(self): """ 算法:1.设置中间列表,遍历n-1次从队列出列,值存入中间列表 2.遍历n-1次,从中间列表倒着入列 :return: 反转后的队列 """ if self.is_empty(): raise QueueError("queue is empty") middle_list = [] len_iterator = len(self._elems)-1 for i in range(len_iterator): middle_list.append(self.dequeue()) for i in range(len_iterator): self.enqueue(middle_list.pop()) print("-"*30) if __name__ == "__main__": sq = SeqQueue() #sq.out_queue() # sq.enqueue(1) # sq.enqueue(2) # sq.enqueue(3) # sq.enqueue(4) # sq.print_queue() # sq.dequeue() #sq.print_queue() # list01 = [] # for i in range(2): # list01.append(sq.dequeue()) # for i in range(2): # sq.enqueue(list01[-i-1]) sq.reverse_queue() sq.print_queue()