当前位置:网站首页>LeetCode:622. 设计循环队列【模拟循环队列】
LeetCode:622. 设计循环队列【模拟循环队列】
2022-08-02 19:22:00 【星空皓月】
题目描述

思路
模拟循环队列即可,具体看代码注释
AC代码
class MyCircularQueue:
q = [0]
num = 0 # 当前队列元素个数
st = 0 # 队头, 队尾st + num - 1
len = 0 # 队列总大小
# 初始化循环队列大小
def __init__(self, k: int):
self.len = k
self.q = [0] * k # 初始化数组
# 入队
def enQueue(self, value: int) -> bool:
if self.isFull(): # 队满
return False
self.num += 1 # 队列元素个数+1
self.q[(self.st + self.num - 1) % self.len] = value # 将元素加入到队尾
return True
# 出队
def deQueue(self) -> bool:
if self.isEmpty(): # 队空
return False
self.num -= 1 # 队列元素个数-1
self.st = (self.st + 1) % self.len # 删除队首元素
return True
# 返回队首元素
def Front(self) -> int:
if self.isEmpty():
return -1
return self.q[self.st]
# 返回队尾元素
def Rear(self) -> int:
if self.isEmpty():
return -1
return self.q[(self.st + self.num - 1) % self.len]
# 判断队列是否为空
def isEmpty(self) -> bool:
if self.num == 0:
return True
return False
# 判断是否队满
def isFull(self) -> bool:
if self.num == self.len:
return True
return False
# 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()
边栏推荐
猜你喜欢
随机推荐
golang刷leetcode 经典(11) 朋友圈
【C语言刷题】Leetcode238——除自身以外数组的乘积
Detailed explanation of common examples of dynamic programming
2022-07-27
线程池原理与实践|从入门到放弃,深度解析
如何获取EasyCVR平台设备通道的RTMP视频流地址?
golang刷leetcode动态规划(12)最小路径和
研发了 5 年的时序数据库,到底要解决什么问题?
MySQL安装配置教程(超级详细)
如何ES源码中添加一个自己的API 流程梳理
JVM内存和垃圾回收-05.虚拟机栈
如何正确地配置入口文件?
golang刷leetcode 经典(12) 完全二叉树插入器
JVM内存和垃圾回收-06.本地方法栈
JWT学习
A Review of Nature Microbiology: Focusing on the Algae--Ecological Interface of Phytoplankton-Bacteria Interactions
JVM内存和垃圾回收-04.程序计数器(PC寄存器)
es 读流程源码解析
分享一个 web 应用版本监测 (更新) 的工具库
Metaverse 001 | Can't control your emotions?The Metaverse is here to help you









