使用Java实现数组模拟环形队列
给出了队列是否满 队列中有效元素等函数和判断条件
package baoxinhai_test_datastructure;
import java.util.Scanner;
/*
* 使用数组模拟环形队列 环形队列预留一个元素 即元素的最大数为maxsize-1
* @author bxh
*/
public class CircleArrayQueue {
public static void main(String[] args) {
CircleQueue queue = new CircleQueue(4); //最大的有效元素为3个
boolean flag=true;
Scanner input=new Scanner(System.in);
char key=' ';
while(flag)
{
System.out.println("输入s(show)显示队列:");
System.out.println("输入a(add)添加元素:");
System.out.println("输入g(get)取出队列中的元素:");
System.out.println("输入h(head)打印队列尾部元素:");
System.out.println("输入e(exit)退出循环:");
key=input.next().charAt(0);
switch (key) {
case 's':
queue.show();
break;
case 'a':
try {
System.out.println("请输入需要添加到队列中的元素:");
int value=input.nextInt();
queue.addqueue(value);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
break;
case 'g':
try {
int x=queue.getqueue();
System.out.println("取出的元素是"+x);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int y=queue.showback();
System.out.println("队列头部的元素为"+y);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
flag=false;
break;
default:
break;
}
}
input.close();
System.out.println("程序退出!");
}
}
class CircleQueue
{
private int maxsize;
private int rear;
private int front;
public int[] queue;
public CircleQueue(int maxsize1) {
maxsize=maxsize1;
queue=new int[maxsize];
}
//判断是否为空
public boolean isempty() {
return rear==front;
}
//判断队列是否已经满了
public boolean isfull()
{
return (rear+1)%maxsize==front;
}
//往队列中添加数据
public void addqueue(int x) {
if(isfull()) //先判断队列是否满
{
throw new RuntimeException("队列已经满了,无法再继续添加队列!");
}
queue[rear]=x;
rear=(rear+1)%maxsize;
}
//取出队列中的元素
public int getqueue() {
if(isempty())
{
throw new RuntimeException("队列为空,目前没有元素可以取出!");
}
int value=queue[front];
front++;
return value;
}
//展示队列中的元素
public void show() {
if(isempty())
{
System.out.println("当前队列中没有元素");
}
for(int i=front;i<front+size();i++)
{
System.out.printf("queue[%d]=%d",i%maxsize,queue[i%maxsize]);
System.out.println();
}
}
//返回当前队列中的有效元素个数
public int size() {
return (rear+maxsize-front)%maxsize;
}
//展示队头的元素
public int showback() {
if(isempty())
{
throw new RuntimeException("队列为空,目前没有元素可以展示!");
}
return queue[front];
}
}