package com;
import com.sun.jmx.remote.internal.ArrayQueue;
import org.omg.CORBA.portable.IDLEntity;
import org.omg.SendingContext.RunTime;
import java.util.Scanner;
//数组模拟队列
public class QueueArray {
private int MaxSize;
private int rear;
private int front;
private int []arr;
public static void main(String[] args) {
//创建队列
QueueArray arr= new QueueArray(2);
char key=' '; //接收用户输入
Scanner sc=new Scanner(System.in);
boolean loop=true;
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):退出");
//输出一个菜单
while(loop)
{
key=sc.next().charAt(0); //接收一个字符
switch (key){
case's':
arr.show();
break;
case'a':
System.out.println("输入一个数:");
int value=sc.nextInt();
arr.add(value);
break;
case'g':
try{
int res=arr.get();
System.out.printf("%d",res);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case'h':
try{
int res=arr.head();
System.out.printf("%d",res);
}
catch (Exception e){
System.out.println(e.getMessage());
}
break;
case'e':
sc.close();
loop=false;
break;
default:
break;
}
}
System.out.println("程序退出");
}
//创建队列
public QueueArray(int arrMaxSize){
MaxSize=arrMaxSize;
arr=new int[MaxSize];
front=-1; //指向队列头的前一个位置
rear=-1; //指向队尾
}
//判断队列是否为满
public boolean isFull(){
return rear==MaxSize-1;
}
//是否为空
public boolean isEmpty(){
return rear==front;
}
//添加数据
public void add(int n){
if(isFull())
{
System.out.println("队列满了,不能加入");
return;
}else{
rear++;
arr[rear]=n;
}
}
//取出数据
public int get(){
if(isEmpty())
{
//通过抛出异常来处理
throw new RuntimeException("队列空,不能取出数据");
}
else{
front++;
return arr[front];
}
}
//显示当前数据
public void show(){
//遍历
if(isEmpty())
{
System.out.println("队列空");
}
else{
for(int i=0;i<arr.length;i++)
System.out.printf("arr[%d]=%d\n",i,arr[i]);
}
}
//显示队列头数据
public int head(){
if(isEmpty())
{
throw new RuntimeException("没有数据");
}
return arr[front+1];
}
}
数组模拟队列
最新推荐文章于 2021-03-28 13:12:10 发布