当前位置:网站首页>LeetCode - 622 设计循环队列 (设计)
LeetCode - 622 设计循环队列 (设计)
2022-07-25 15:32:00 【三岁就很萌@D】


数组来实现队列

头指针指向当前头元素的上一个位置 尾指针指向尾元素
class MyCircularQueue {
private int[] queue;//队列数组
private int size;//队列中实际存放了多少元素
private int head;//头指针
private int tail;//尾指针
private int capacity;//队列固定大小
public MyCircularQueue(int k) {
//队列固定大小为k
this.queue = new int[k];
this.size = 0;
this.head = 0;
this.tail = 0;
this.capacity = k;
}
public boolean enQueue(int value) {
if(isFull())//队列满了 值不能入队列
return false;
else{
//将值放入队列尾部
queue[tail] = value;
//队列大小加一
size += 1;
//尾指针向后移动
tail = (++tail) % this.capacity;
return true;
}
}
public boolean deQueue() {
//如果队列为空 值出队列失败
if(isEmpty())
return false;
else{
//头指针向后移动
head = (++head) % this.capacity;
//队列大小减一
size -= 1;
return true;
}
}
public int Front() {
if(isEmpty())
return -1;
else
//返回头指针对应值
return queue[head];
}
public int Rear() {
if(isEmpty())
return -1;
else{
// tail指向的是当前要存数的位置 所以队列中实际的最后一个数是tail的上一个位置
int rear = (tail - 1 + this.capacity) % this.capacity;
return queue[rear];
}
}
public boolean isEmpty() {
//判断队列的实际容量是否为0
return this.size == 0;
}
public boolean isFull() {
//判断队列中数的实际个数是否与队列容量相等
return this.size == this.capacity;
}
}
/** * Your MyCircularQueue object will be instantiated and called as such: * MyCircularQueue obj = new MyCircularQueue(k); * boolean param_1 = obj.enQueue(value); * boolean param_2 = obj.deQueue(); * int param_3 = obj.Front(); * int param_4 = obj.Rear(); * boolean param_5 = obj.isEmpty(); * boolean param_6 = obj.isFull(); */
边栏推荐
猜你喜欢

带你创建你的第一个C#程序(建议收藏)

理解“平均负载”

wait()和sleep()的区别理解

Pat grade a 1152 Google recruitment (20 points)

ML - 自然语言处理 - 基础知识

Pytorch学习笔记--SEResNet50搭建

JVM知识脑图分享

Phased summary of the research and development of the "library management system -" borrowing and returning "module

PAT甲级1152 Google Recruitment (20 分)

Reflection - Notes
随机推荐
Spark SQL UDF function
C # fine sorting knowledge points 9 Set 2 (recommended Collection)
ML - natural language processing - Key Technologies
2021上海市赛-B-排序后dp
2021 Shanghai sai-d-cartland number variant, DP
Delayed loading source code analysis:
Get the ask code corresponding to the key pressed by the keyboard
Seata中jdbc下只有一个lib嘛?
Node learning
2016 CCPC network trial c-change root DP good question
Cf685b find the center of gravity of each subtree of a rooted tree
Application of C language array in Sanzi chess -- prototype of Queen n problem
Take you to create your first C program (recommended Collection)
JVM-动态字节码技术详解
Distributed principle - what is a distributed system
pageHelper不生效,sql没有自动加上limit
How to understand the maximum allowable number of errors per client connection of MySQL parameters in Seata?
2021 Jiangsu race a Array line segment tree, maintain value range, Euler power reduction
带你创建你的第一个C#程序(建议收藏)
Spark AQE