思路:
push, head + 1
tail + 1
len(Queue) <= array_size
# -*- coding:utf-8 -*- # Author: Greed_Vic(PL Z) # Product_name: PyCharm # File_name: arrayQ # @Time: 21:23 2021/6/8 class Array(object): """ 定义一个数组 """ def __init__(self, size=32): self._size = size # 设置数组长度 self._items = [None] * size # 开辟数组,初始None def __getitem__(self, index): return self._items[index] # 特殊方法,用来获取此下标的元素 def __setitem__(self, index, value): self._items[index] = value # 特殊方法,用来赋值? def __len__(self): return self._size # 特殊方法,获取长度 接受 len(array) def __iter__(self): for item in self._items: # 特殊方法, 接受迭代 yield item def clear(self, value=None): for i in range(self._items): self._items[i] = value # 重置 class ArrayQueue(object): """ 数组队列 """ def __init__(self, maxsize=18): self.maxsize = maxsize self.array = Array(maxsize) self.head = 0 self.tail = 0 def push(self, val): if self.head - self.tail >= self.maxsize: # 长度队列已经满了 raise Exception('Full ArrayQueue') self.array[self.head % self.maxsize] = val # 利用取模的方式进行获取位置 self.head += 1 # 入队一个 head 加一 def pop(self): if self.tail >= self.head: raise Exception('Empty ArrayQueue, you should push val first!') # pop操作只能在有数据的情况下进行 val = self.array[self.tail % self.maxsize] self.tail += 1 return val def __len__(self): return self.head - self.tail # 外界可用 len()方法进行获取长度 if __name__ == '__main__': """ 单测 """ def testAQ(): size = 5 q = ArrayQueue(size) for i in range(size): print(q.head, q.tail) assert len(q) == size assert q.pop() == 0 assert q.pop() == 1 q.push(9) assert len(q) == 4 assert q.pop() == 2 assert q.pop() == 3 assert q.pop() == 4 assert q.pop() == 9 print("Test Done!") testAQ()