分析
循环队列,自己做题时没考虑怎么实现,可以通过索引下标除以数组的长度实现循环。循环队列的队首元素和队尾元素是动态变化的,删除一个队首元素后,此时队首元素变为下一元素。
对于一个固定大小的数组,任何位置都可以是队首,只要知道队列长度,就可以根据下面公式计算出队尾位置:
其中 capacity 是数组长度(题目要求的长度),count 是队列长度(实际元素的个数),headIndex 和 tailIndex 分别是队首 head 和队尾 tail 索引。
代码
class MyCircularQueue:
def __init__(self, k: int):
self.queue = [-1] * k
self.start = 0
# 记录队列中有效元素的个数
self.count = 0
self.size = k
def enQueue(self, value: int) -> bool:
if self.count == self.size:
return False
# 先加1,方便后面队尾索引计算
self.count += 1
last = (self.start + self.count - 1) % self.size
self.queue[last] = value
return True
def deQueue(self) -> bool:
if self.count == 0:
return False
# 删除队首元素之后,队首元素变为下一元素
self.count -= 1
self.start = (self.start + 1) % self.size
return True
def Front(self) -> int:
if self.count == 0:
return -1
return self.queue[self.start]
def Rear(self) -> int:
if self.count == 0:
return -1
last = (self.start + self.count - 1) % self.size
return self.queue[last]
def isEmpty(self) -> bool:
return self.count == 0
def isFull(self) -> bool:
return self.count == self.size
myCircularQueue = MyCircularQueue(3)
print(myCircularQueue.enQueue(1))
print(myCircularQueue.enQueue(2))
print(myCircularQueue.enQueue(3))
print(myCircularQueue.enQueue(4))
print(myCircularQueue.Rear())
print(myCircularQueue.isFull())
print(myCircularQueue.deQueue())
print(myCircularQueue.enQueue(4))
print(myCircularQueue.Rear())
参考链接
https://leetcode-cn.com/problems/design-circular-queue/solution/she-ji-xun-huan-dui-lie-by-leetcode/