循环队列
队列:队列是一种先进先出的线性表,它只允许在表的一端进行插入,而另一端进行删除,允许插入的一端叫做队尾,允许删除的一端叫做对头。
循环队列;
循环队列是一种以顺序存储结构表示的队列,为了解决“假溢出”问题而将它设计成头尾相接的循环结构,它的基本操作如下:
1、初始化循环队列
2、销毁循环队列
3、清空循环队列
4、检测循环队列是否为空
5、返回循环队列的元素个数
6、返回循环队列头元素
7、向队尾插入元素
8、删除并返回队头元素
9、遍历循环队列
在循环队列中,除了用一组地址连续的存储单元依次存储从队头到队尾的元素外,还需要附设两个整型变量front和rear分别指示队头和队尾的位置。
1、定义类属性和构造函数
class InitQueue{ private int [] queue = null; private int front = 0; private int rear = 0; private boolean empty = true; //true表示循环队列为空 public InitQueue(int max) { //构造指定大小的循环队列 this.queue = new int[max]; } }
2、清空循环队列
public void clearQueue() { this.front = 0; this.rear = 0; this.empty = true; }
3、检测循环队列是否为空
public boolean queueEmpty() { if(this.empty == true) { return true; }else { return false; } }
4、返回循环队列的元素个数
public int queueLength() { //如果循环队列已满,返回数组长度即元素个数 if (this.front == this.rear && this.empty == false) { return this.queue.length; } //否则,取模运算得到长度 return (this.rear - this.front + this.queue.length) % this.queue.length; }
5、返回循环队列头元素
public int [] getHead() { if (this.empty == true) { return null; } int [] i = new int[1]; i[0] = queue[this.front]; return i; }
6、向队尾插入元素
public boolean enQueue(int value) { if (this.empty == false && this.front == this.rear) { return false; } this.queue[this.rear] = value; this.rear = (this.rear + 1) % this.queue.length; this.empty = false; return true; }
7、删除并返回队头元素
public int [] deQueue() { if (this.empty == true) { return null; } int [] i = new int[1]; //获取队头元素 i[0] = this.queue[this.front]; //删除队头元素(front指针加一) this.front = (this.front + 1) % this.queue.length; //如果循环队列变空,改变标志位 if(this.front == this.rear) { this.empty = true; } return i; }
8、遍历循环队列
public String queueTraverse() { //此处用输出循环队列表示遍历 String s = ""; //i指向第一个元素 int i = this.front; //如果循环队列已满,取出第一个元素,i指向下一个元素 if(this.front == this.rear && this.empty == false) { s += this.queue[i] + "、"; i = (i + 1) % this.queue.length; } //如果未到末尾,则循环读取元素 while (i != this.rear) { s += this.queue[i] + "、"; i = (i + 1) % this.queue.length; } //如果没有读取到元素,直接返回空字符串 if(s.length() == 0) { return s; } //除去最后的顿号返回 return s.substring(0,s.length() - 1); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了