The following editor will bring you an example of using an array to implement a circular queue in Java. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
I reviewed the data structure and used Java arrays to implement a circular queue.
Queue class
//循环队列 class CirQueue{ private int QueueSize; private int front; private int rear; private int[] queueList ; public CirQueue(int QueueSize){ this.QueueSize = QueueSize; queueList = new int[QueueSize]; front = 0; rear = 0; } //获取队列头元素 public int getQueueElement(){ //如果队列不为空,返回队头元素,否则抛出异常提示队列为空 int element = -1; if(!isEmpty()){ element = queueList[front]; return element; } else { System.out.println("队列为空"); return -1; } } //出队 public int deQueue(){ int element = -1; if(!isEmpty()){ element = queueList[front]; front =(front+1)%QueueSize; return element; } else { System.out.println("队列为空"); return -1; } } //入队 public void enQueue(int element){ //如果队列未满,添加元素到队尾,否则提示队列已满 if(!isFull()){ queueList[rear] = element ; rear = (rear+1)%QueueSize; } else { System.out.println("队列已满"); } } //判断队列是否为空 public boolean isEmpty(){ boolean b = false; if(rear == front) b = true; return b; } //判断队列是否已满 public boolean isFull(){ boolean b = false; if((rear+1)%QueueSize == front) b = true; return b; } }
Create object and test
package com.test; import java.util.*; public class StructTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //新建并初始化存储空间为3的循环队列(方便判断队满条件,浪费一个数组空间) CirQueue cirQueue = new CirQueue(4); //入队3个元素 cirQueue.enQueue(1); cirQueue.enQueue(2); cirQueue.enQueue(3); //获取队头元素,获取 但不改变队列 int temp = cirQueue.getQueueElement(); System.out.println(temp); //出队 获取队头元素,并且队头指针往后移一位 temp = cirQueue.deQueue(); System.out.println(temp); //再次获取队头元素 temp = cirQueue.getQueueElement(); System.out.println(temp); } }
Output:
1 1 2
The above is the detailed content of A case study on how Java uses arrays to implement circular queues. For more information, please follow other related articles on the PHP Chinese website!