当前位置:网站首页>如何设计循环队列?快进来学习~
如何设计循环队列?快进来学习~
2022-08-01 23:58:00 【陈亦康】
分析:
两种解题思路,一种是计数法,还有一种是浪费空间法,为什么这么说呢,看下图:
解法一:
class MyCircularQueue {
public int[] array;
private int front;
private int rear;
private int usedSize;
public MyCircularQueue(int k) {
array = new int[k];
}
//插入数据
public boolean enQueue(int value) {
if(isFull()){
return false;
}
else{
array[rear] = value;
//不可以单纯的rear++;会溢出,就不是循环了
rear = (rear + 1) % array.length;
usedSize++;
return true;
}
}
//删除元素
public boolean deQueue() {
if(isEmpty()){
return false;
}
front = (front + 1) % array.length;
usedSize--;
return true;
}
//获取首元素
public int Front() {
if(isEmpty()){
return -1;
}
return array[front];
}
//获取尾元素
public int Rear() {
if(isEmpty()){
return -1;
}
return rear == 0 ? array[array.length - 1] : array[rear - 1];
}
//检查是否为空
public boolean isEmpty() {
if(usedSize == 0){
return true;
}
return false;
}
//是否为满
public boolean isFull() {
return usedSize == array.length;
}
}
解法二:
class MyCircularQueue {
public int[] array;
private int front;
private int rear;
public MyCircularQueue(int k) {
array = new int[k + 1];
}
//插入数据
public boolean enQueue(int value) {
if(isFull()){
return false;
}
else{
array[rear] = value;
//不可以单纯的rear++;会溢出,就不是循环了
rear = (rear + 1) % array.length;
return true;
}
}
//删除元素
public boolean deQueue() {
if(isEmpty()){
return false;
}
front = (front + 1) % array.length;
return true;
}
//获取首元素
public int Front() {
if(isEmpty()){
return -1;
}
return array[front];
}
//获取尾元素
public int Rear() {
if(isEmpty()){
return -1;
}
return rear == 0 ? array[array.length - 1] : array[rear - 1];
}
//检查是否为空
public boolean isEmpty() {
if(rear == front){
return true;
}
return false;
}
//是否为满
public boolean isFull() {
return (rear + 1) % array.length == front;
}
}
边栏推荐
- The Spark of Sql join on the and and where
- FAST-LIO2 code analysis (2)
- 一款简洁的文件传输工具
- Detailed explanation of Zadig's self-testing and tuning environment technical solution for developers
- cdh6 opens oozieWeb page, Oozie web console is disabled.
- 如何进行数据库备份
- 【三子棋】C语言实现简易三子棋
- UI自动化测试框架搭建-标记性能较差用例
- 软件测试之移动APP安全测试简析,北京第三方软件检测机构分享
- 【MySQL篇】初识数据库
猜你喜欢
随机推荐
根本上解决mysql启动失败问题Job for mysqld.service failed because the control process exited with error code
yay 报错 response decoding failed: invalid character ‘<‘ looking for beginning of value;
2022 6th Strong Net Cup Part WP
@Transactional注解在类上还是接口上使用,哪种方式更好?
Work for 5 years, test case design is bad?To look at the big case design summary
TCP 可靠吗?为什么?
【无标题】
ansible模块--copy模块
A brief analysis of mobile APP security testing in software testing, shared by a third-party software testing agency in Beijing
Chrome书签插件,让你实现高效整理
background-image使用
在CDH的hue上的oozie出现,提交 Coordinator My Schedule 时出错
【ACWing】230. 排列计数
【MySQL系列】MySQL索引事务
Flink学习第四天——完成第一个Flink 流批一体案例
【Leetcode】470. Implement Rand10() Using Rand7()
DOM 事件及事件委托
WEB安全基础 - - - XRAY使用
Thinkphp 5.0.24变量覆盖漏洞导致RCE分析
月薪12K,蝶变向新,勇往直前—她通过转行测试实现月薪翻倍~