队列是有序列表,使用数组结构来存储队列的数据。
队列的入队一般使用addQueue,addQueue的处理需要两个步骤。
此处使用一个数组来模拟队列操作
public class ArrayQueueDemo {
public static void main(String[] args) {
//创建一个对象
ArrayQueue aq=new ArrayQueue(3);
char key = ' ';//用于接收用户数据
Scanner sc = new Scanner(System.in);
boolean loop = true;
//输出一个菜单
while(loop) {
System.out.println("s(show):显示队列");
System.out.println("e(exit):退出队列");
System.out.println("a(add):添加数据到队列");
System.out.println("g(get):从队列取出数据");
System.out.println("h(head):查看队列头的数据");
key = sc.next().charAt(0);//接去第一个字符
switch(key) {
case 's': //展示队列数据
aq.showQueue();
break;
case 'a': //向队列添加数据
System.out.println("请输入一个数");
int value = sc.nextInt();
aq.addQueue(value);
break;
case 'g': //获得队列的数据
try {
int res = aq.getQueue();
System.out.printf("取出的数据实%d\n",res);
aq.getQueue();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h': //查看队列头的数据
try {
int res = aq.headQueue();
System.out.printf("取出的数据实%d\n",res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
case 'e': //代表要退出
sc.close();
loop = false;
break;
default:
break;
}
}
System.out.println("程序退出");
}
}
//使用数组模拟队列,编写一个ArrayQueue类
class ArrayQueue{
private int maxSize;//设置数组的最大容量
private int front;//队列头
private int rear;//队列尾部
private int [] arr;//该数据用于存放数据,模拟队列
//创建队列的构造器
public ArrayQueue(int arrMaxSize) {
maxSize = arrMaxSize;
arr = new int [maxSize];
front = -1; //指向队列头部,指向队列头的前一个位置
rear = -1; //指向队列尾部,队列尾部包含对象最后一个数据,通俗的讲就是队列最后一个位置
}
//判断队列是否满
public boolean isFull() {
return rear == maxSize - 1;
}
//判断队列是否为空
public boolean isNull() {
return rear == front;
}
//数据是否添加到队列
public void addQueue(int n) {
//判读队列是否满
if(isFull()) {
System.out.println("队列满,不能加入数据");
return;
}
rear ++ ; //让rear 后移动
arr[rear] = n;
}
//判读队列的数据,出队列
public int getQueue() {
//判读队列是否为空
if(isNull()) {
//抛出异常
throw new RuntimeException("队列为空,不能获取数据");
}
front ++;
return arr[front];
}
//显示队列所有数据
public void showQueue() {
//将数组数据遍历
if(isNull()) {
System.out.println("队列为空,没有数据");
return;
}
for(int i = 0; i < arr.length; i++ ) {
System.out.printf("arr[%d]=%d\n",i,arr[i]);
}
}
//显示队列的头数据,注意不是取出数据
public int headQueue() {
//判断
if(isNull()) {
throw new RuntimeException("队列空,没有数据");
}
return arr[front + 1];
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/197975.html