当前位置:网站首页>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;}}
边栏推荐
猜你喜欢
使用Ganache、web3.js和remix在私有链上部署并调用合约
Using the "stack" fast computing -- reverse polish expression
How to reinstall Win11?One-click method to reinstall Win11
协作乐高 All In One:DAO工具大全
【加密周报】经济衰退在加息气氛中蔓延 美联储“放手一搏”?盘点上周加密市场发生的重大事件
认识USB、Type-C、闪电、雷电接口
Win10安装DBeaver连接MySQL8、导入和导出数据库详细教程
面试必问的HashCode技术内幕
工件SSMwar exploded 部署工件时出错。请参阅服务器日志了解详细信息
async和await用法介绍
随机推荐
已知中序遍历数组和先序遍历数组,返回后序遗历数组
Docker实践经验:Docker 上部署 mysql8 主从复制
REST会消失吗?事件驱动架构如何搭建?
els 长条变形
How to solve the error when mysql8 installs make
协作乐高 All In One:DAO工具大全
windows sql server 如何卸载干净?
不了解SynchronousQueue?那ArrayBlockingQueue和LinkedBlockingQueue不会也不知道吧?
正则表达式
TCP 可靠吗?为什么?
OpenCV DNN blogFromImage() detailed explanation
els block deformation
mysql8安装make报错如何解决
信息系统项目管理师必背核心考点(五十七)知识管理工具
如何重装Win11?一键重装Win11方法
JSP如何使用page指令让JSP文件支持中文编码呢?
background-image使用
Docker搭建Mysql主从复制
thinkphp漏洞总结
Thinkphp 5.0.24变量覆盖漏洞导致RCE分析