package baoxinhai_test_datastructure;
import java.util.Scanner;
/*
*使用数组模拟一个队列 并且实现判断 存取数据等操作
*@author bxh
*/
public class Arrayqueue {
public static void main(String[] args) {
queue queue = new queue(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 queue{
// 定义队列的最大容量 头部和尾部的指针
private int maxsize;
private int rear;
private int front;
public int[] queue;
//初始化队列
public queue(int maxsize1) {
// TODO Auto-generated constructor stub
maxsize=maxsize1;
queue=new int[maxsize];
rear=-1;
front=-1;
}
//判断是否为空
public boolean isempty() {
return rear==front;
}
//判断队列是否已经满了
public boolean isfull()
{
return rear==maxsize-1;
}
//往队列中添加数据
public void addqueue(int x) {
if(isfull()) //先判断队列是否满
{
throw new RuntimeException("队列已经满了,无法再继续添加队列!");
}
rear++;
queue[rear]=x;
}
//取出队列中的元素
public int getqueue() {
if(isempty())
{
throw new RuntimeException("队列为空,目前没有元素可以取出!");
}
front++;
return queue[front];
}
//展示队列中的元素
public void show() {
for(int i=front+1;i<=rear;i++)
{
System.out.printf("queue[%d]=%d",i,queue[i]);
System.out.println();
}
}
//展示队尾的元素
public int showback() {
if(isempty())
{
throw new RuntimeException("队列为空,目前没有元素可以展示!");
}
return queue[front+1];
}
}