public class Duilie {
//队列特性:先进先出
public static void main(String[] args) {
Data data = new Data(5);
data.add(1);
data.add(3);
data.add(5);
data.add(7);
data.add(2);
data.add(9);
int push = data.push();
System.out.println("抛出的节点为:"+push);
data.show();
System.out.println("头节点为:"+data.showHead());
}
}
class Data{
private int max;
private int font; //列头
private int rear; //列尾
private int[] arr;
//构造器
public Data(int max) {
font=-1;
rear=-1;
this.max = max;
arr=new int[max];
}
// 判断是否已满
public boolean full() {
return rear==max-1;
}
//判断是否为空
public boolean empty() {
return rear==font;
}
//添加元素
public void add(int n) {
if(full()){
System.out.println("队列已满");
return;
}
rear++;
arr[rear]=n;
}
//抛出元素 返回抛出的元素
public int push(){
if(empty()){
throw new RuntimeException("队列已空");
}
font++;
return arr[font];
}
//遍历元素
public void show() {
if(empty()){
System.out.println("队列为空!");
return;
}
for (int i = font+1; i <rear+1 ; i++) {
System.out.printf("arr[%d]=%d\n",i,arr[i]);
}
}
//显示头节点
public int showHead() {
if (empty()){
throw new RuntimeException("队列为空");
}
return arr[font+1];
}
}
java 用数组模拟队列
最新推荐文章于 2022-07-14 16:45:18 发布