队列的特点是先进先出,我们使用数组来实现以下队列
import java.util.Scanner;
//使用数组模拟队列
public class quenedemo01 {
public static void main(String[] args) {
ArrayQuene quene = new ArrayQuene(3);
Scanner scanner = new Scanner(System.in);
System.out.println("a----加入数据");
System.out.println("g----取出数据");
System.out.println("e------退出");
System.out.println("s---显示队列");
while (true){
System.out.println("请选择操作:");
char key = scanner.next().charAt(0);
if (key == 'e'){
scanner.close();
System.out.println("欢迎下次再来");
return;
}
if (key == 's'){
quene.show();
continue;
}
if (key == 'a'){
int kk = scanner.nextInt();
quene.add(kk);
continue;
}
if (key == 'g'){
int result = quene.getdata();
if (result != -1){
System.out.println("你得到了:"+result);
}
}
}
}
}
class ArrayQuene{
private int maxsize; //表示数组的最大值
private int front; //队列头
private int rear; //队列尾
private int[] arr; //用于存放数据
//创建队列的构造器
public ArrayQuene(int a){
maxsize = a;
arr = new int[maxsize];
front = -1; //队头
rear = -1; //队尾
}
//判断队列是否满
public boolean isFull(){
return (front == maxsize - 1);
}
//判断队列是否空
public boolean isEmpty(){
return (front == rear);
}
//加入数据
public void add(int n){
if (isFull()){
System.out.println("队列已满");
return;
}
front += 1;
arr[front] = n;
System.out.println("加入"+n+"成功");
}
//删除数据
public int getdata(){
if (isEmpty()){
System.out.println("队列空,没有数据");
return -1;
}
rear += 1;
System.out.println("删除的数据是:"+arr[rear]);
return arr[rear];
}
//显示队列数据
public void show(){
if (isEmpty()){
System.out.println("队列为空,没有数据");
return;
}
System.out.println("队列里有:");
for (int i : arr) {
System.out.print(i+"\t");
}
}
}
注释都写的清楚了,运行结果就不展示了,我已运行成功