数据结构--队列(python实现)
用python实现队列。队列是有序集合,添加操作发生在“尾部”,移除操作则发生在“头部”。新元素从尾部进入队列,然后一直向前移动到头部,直到成为下一个被移除的元素。
代码实现如下:
其中的hotpotato为用队列模拟一个游戏过程,假设队列头部元素被标记,这个标记依次传递给下面的元素,在某个时刻,该元素被弹出!
class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self,item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def show(self): return self.items def hotpotato(namelist,num): simqueue = Queue() for name in namelist: simqueue.enqueue(name) while simqueue.size()>1: for i in range(num): simqueue.enqueue(simqueue.dequeue()) print(simqueue.show()) simqueue.dequeue() return simqueue.dequeue() name = ["A","B","C","D","E","F"] print(hotpotato(name,7))