标准类:
public class ArrayQueue{ //队列,由队尾插入元素,由队首删除元素
private int[] A; //内置数组
private int front; //头指针
private int rear; //尾指针
public ArrayQueue(int size) {
this.A=new int[size];
front=0;
rear=-1; //初始化队列
} //kuimeng
public boolean Empty(){
return front == A.length; //判断队列为空
}
public boolean Full() {
return A.length - 1 == rear; //判断队列为满
}
public void insert(int Element) {
if(Full()) {
throw new Error("队列已满");
} //kuimeng
A[++rear]=Element; //在队列的队尾插入元素
}
public int leader() {
return A[front]; //获取队首元素
}
public int end() {
return A[rear]; //获取队尾元素
}
public int Removal() {
if(Empty()) {
throw new Error("队列为空");
}
return A[front++]; //删除队首元素
}}//kuimeng
测试类:
public class ArrayQueueTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayQueue queue=new ArrayQueue(20);
System.out.println("---------------------------------------------------");
System.out.println("队列是否为空?:"+queue.Empty());
//kuimeng
System.out.println("---------------------------------------------------");
for(int i=0;i<20;i++) {
queue.insert(i);
}
System.out.println("队列是否已满?:"+queue.Full());
System.out.println("---------------------------------------------------");
System.out.println("队首元素为:"+queue.leader());
System.out.println("---------------------------------------------------");
System.out.println("队尾元素为:"+queue.end());
System.out.println("---------------------------------------------------");
System.out.println("队列所有元素为:");
while(!queue.Empty()) { //kuimeng
System.out.println(+queue.Removal());
}
System.out.println("---------------------------------------------------");
}}
运行结果:
---------------------------------------------------
队列是否为空?:false
---------------------------------------------------
队列是否已满?:true
---------------------------------------------------
队首元素为:0
---------------------------------------------------
队尾元素为:19
---------------------------------------------------
队列所有元素为:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
---------------------------------------------------
对小编的代码有兴趣的朋友们记得点赞关注哟~