下面小编就为大家带来一篇Java用数组实现循环队列的示例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
复习了下数据结构,用Java的数组实现一下循环队列。
队列的类
//循环队列 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; } }
创建对象并测试
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); } }
输出:
1 1 2
以上是Java如何使用数组实现循环队列的案例的详细内容。更多信息请关注PHP中文网其他相关文章!