当前位置:网站首页>How to design a circular queue?Come and learn~
How to design a circular queue?Come and learn~
2022-08-02 00:16:00 【Chen Yikang】
Analysis:
There are two ways to solve the problem, one is counting method, and the other is wasting space method, why do you say this, see the picture below:
Solution 1:
class MyCircularQueue {public int[] array;private int front;private int rear;private int usedSize;public MyCircularQueue(int k) {array = new int[k];}//insert datapublic boolean enQueue(int value) {if(isFull()){return false;}else{array[rear] = value;//Can't simply rear++; it will overflow, it is not a looprear = (rear + 1) % array.length;usedSize++;return true;}}// delete elementpublic boolean deQueue() {if(isEmpty()){return false;}front = (front + 1) % array.length;usedSize--;return true;}//get the first elementpublic int Front() {if(isEmpty()){return -1;}return array[front];}//get the tail elementpublic int Rear() {if(isEmpty()){return -1;}return rear == 0 ? array[array.length - 1] : array[rear - 1];}//check if emptypublic boolean isEmpty() {if(usedSize == 0){return true;}return false;}// is it fullpublic boolean isFull() {return usedSize == array.length;}}
Solution 2:
class MyCircularQueue {public int[] array;private int front;private int rear;public MyCircularQueue(int k) {array = new int[k + 1];}//insert datapublic boolean enQueue(int value) {if(isFull()){return false;}else{array[rear] = value;//Can't simply rear++; it will overflow, it is not a looprear = (rear + 1) % array.length;return true;}}// delete elementpublic boolean deQueue() {if(isEmpty()){return false;}front = (front + 1) % array.length;return true;}//get the first elementpublic int Front() {if(isEmpty()){return -1;}return array[front];}//get the tail elementpublic int Rear() {if(isEmpty()){return -1;}return rear == 0 ? array[array.length - 1] : array[rear - 1];}//check if emptypublic boolean isEmpty() {if(rear == front){return true;}return false;}// is it fullpublic boolean isFull() {return (rear + 1) % array.length == front;}}
边栏推荐
- 在MySQL登录时出现Access denied for user ‘root‘@‘localhost‘ (using password YES) 拒绝访问问题解决
- 在不完全恢复、控制文件被创建或还原后,必须使用 RESETLOGS 打开数据库,解释 RESETLOGS.
- GetHashCode与Equals
- 接地气讲解TCP协议和网络程序设计
- 机器学习文本分类
- JSP out.println()方法具有什么功能呢?
- Short video SEO search operation customer acquisition system function introduction
- els 方块变形判断。
- 扑克牌问题
- 正则表达式
猜你喜欢
随机推荐
JSP out.print()和out.write()方法的不同之处
[头条]笔试题——最小栈
洞见云原生微服务及微服务架构浅析
async/await 原理及执行顺序分析
【MySQL系列】MySQL数据库基础
【MySQL系列】MySQL索引事务
【Leetcode】479. Largest Palindrome Product
【ACWing】230. 排列计数
很多人喜欢用多御安全浏览器,竟是因为这些原因
Flink Yarn Per Job - CliFrontend
Using the "stack" fast computing -- reverse polish expression
【无标题】
【MySQL系列】 MySQL表的增删改查(进阶)
TCL:在Quartus中使用tcl脚本语言进行管脚约束
EasyExcel的简单读取操作
LeetCode_279_完全平方数
【图像融合】基于加权和金字塔实现图像融合附matlab代码
12306抢票,极限并发带来的思考?
扑克牌问题
WEB安全基础 - - - XRAY使用