# 数组有一个固定的长度。头指针和尾指针,都指向数组第一个值。# 当进行push操作的时候,头指针后移。当进行pop操作的时候,尾指针向后移# 当到达最后一个值的时候,重新指向第一个值。取模 %queue_size()# 首先实现一个数组class Array(object): def __init__(self,size = 32): self._size = size self._items = [None] * size # 容器_items, 是一个每个值为None的列表 def __getitem__(self, index): # 实现下标访问 return self._items[index] def __setitem__(self, index, value): self._items[index] = value def __len__(self): return self._size def clear(self, value=None): for i in range(len(self._items)): self._items[i] = value def __iter__(self): for item in self._items: yield itemclass ArrayQueue(object): def __init__(self, maxsize): self.maxsize = maxsize self.array = Array(maxsize) self.head = 0 self.tail = 0 def push(self, value): if len(self) >= self.maxsize: raise Exception('queue full') self.array[self.head % self.maxsize] = value self.head += 1 def pop(self): value = self.array[self.tail % self.maxsize] self.tail += 1 return value def __len__(self): return self.head - self.taildef test_arrrayqueue(): import pytest size = 5 q = ArrayQueue(size) for i in range(size): q.push(i) assert len(q) == size assert q.pop() == 0 assert q.pop() == 1 q.push(5) assert len(q) == 4 assert q.pop() == 2 assert q.pop() == 3 assert q.pop() == 4 assert q.pop() == 5 assert len(q) == 0