难度: 中等
题目分析: 看下面代码实现。参考的是裘宗燕的《数据结构与算法:Python语言描述》。此处不建议使用python内置的list的append, pop操作,使用了就违背设计循环队列的初衷:消除代价为O(n)的出队操作。
class MyCircularQueue:
def __init__(self, k: int):
"""
Initialize your data structure here. Set the size of the queue to be k.
"""
# 入队在位置 head + num % len; 满的话,num == len; 空的话,num == 0
self.head = 0
self.num = 0
self.queue = [0]*k
self.len = k
def enQueue(self, value: int) -> bool:
"""
Insert an element into the circular queue. Return true if the operation is successful.
"""
if self.len == self.num: # 满了
return False
self.queue[(self.head + self.num) % self.len] = value
self.num += 1
return True
def deQueue(self) -> bool:
"""
Delete an element from the circular queue. Return true if the operation is successful.
"""
if self.num == 0:
return False
self.head = (self.head + 1) % self.len
self.num -= 1
return True
def Front(self) -> int:
"""
Get the front item from the queue.
"""
if self.num == 0:
return -1
return self.queue[self.head]
def Rear(self) -> int:
"""
Get the last item from the queue.
"""
if self.num == 0:
return -1
return self.queue[(self.head + self.num - 1) % self.len]
def isEmpty(self) -> bool:
"""
Checks whether the circular queue is empty or not.
"""
return self.num == 0
def isFull(self) -> bool:
"""
Checks whether the circular queue is full or not.
"""
return self.num == self.len
# Your MyCircularQueue object will be instantiated and called as such:
# obj = MyCircularQueue(k)
# param_1 = obj.enQueue(value)
# param_2 = obj.deQueue()
# param_3 = obj.Front()
# param_4 = obj.Rear()
# param_5 = obj.isEmpty()
# param_6 = obj.isFull()
运行结果:
代码后面注释掉的调用部分,是可以在准备设计一个数据结构前就想好的,先明白我们使用的时候要怎么调用,再来设计数据结构,会事半功倍。同时,完成设计后,这部分代码,就可以转化为测试代码,确保每个功能都测试到。