赞
踩
先进先出 FIFO,在非空队列中,队首指针指向队头元素,队尾指针指向队尾元素的下一个位置。
顺序队列中的假溢出现象:(front:头指针,rear:尾指针)
循环队列充分利用了系统分配的空间,克服了“假溢出”现象。方法:将队列看成是一个首尾相接的圆环。
约定:rear所指的位置始终为空
队列为空时:front == rear;
队列满时:(rear+1) % size == front;(size:队列的空间大小)
- class CQue{
- //循环队列
-
- private int size = 5;
- private int[] array;
- int front,rear;
-
- public CQue() {
- array = new int[this.size];
- front = rear =0;
- }
-
- /**
- * 入队
- * @param data
- * @throws Exception
- */
- public int insert(int data) throws Exception {
- if (isFull()) {
- throw new Exception("queue is full !");
- }
- this.array[rear] = data;
- this.rear = (this.rear+1)%this.size;//移动队尾指针
- return this.rear;//返回队尾指针的位置
- }
-
- /**
- * 出队
- * @return
- * @throws Exception
- */
- public int remove() throws Exception {
- if (isEmpty()) {
- throw new Exception("queue is empty !");
- }
- int data =array[front]; //获取队首元素
- this.front = (this.front+1)%this.size;//移动队首指针
- return data;
-
- }
-
- /**
- * 判断是否为空
- * @return
- */
- public boolean isEmpty() {
- return this.front == this.rear;
- }
-
- /**
- * 判断队列是否满了
- * @return
- */
- public boolean isFull() {
- return ((this.rear + 1) % this.size) == this.front;
- }
-
- public int getSize() {
- return size;
- }
- public void setSize(int size) {
- this.size = size;
- }
- }
-
- public class MyQueue {
-
- public static void main(String[] args) throws Exception {
- CQue queue = new CQue();
- System.out.println(queue.getSize() + "--"+queue.isEmpty() +"--"+queue.isFull());
- System.out.println(queue.insert(0));
- System.out.println(queue.insert(1));
- System.out.println(queue.insert(2));
- System.out.println(queue.insert(3));
- System.out.println(queue.isFull());
- //queue.insert(4);
- //System.out.println(queue.isFull());
- System.out.println(queue.remove());
- System.out.println(queue.remove());
- System.out.println(queue.remove());
- System.out.println(queue.remove());
- System.out.println(queue.remove());
-
- }
-
- }
-
-
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。