test.java
public class test{ public static void main(String[] args) { //创建一个队列 ArrayQueue1 a = new ArrayQueue1(); a.creatArrayQueue(5); System.out.println(a.isEmpty()); a.addQueue(1); a.addQueue(3); a.getQueue(); a.showQueue(); System.out.println("-------------"); a.addQueue(5); a.addQueue(7); a.addQueue(3); a.showQueue(); System.out.println(a.isFull());//此时虽然队列中的有效数字只有4个,不到5个,但是rear指针已经移到了maxSize-1的位置了。 } }
ArrayQueue1.javapublic class ArrayQueue1 private int maxSize;//最大容量
private int front;//队列头 private int rear;//队列尾 private int arr[]; //创建队列 public void creatArrayQueue(int arrMaxSize) { maxSize = arrMaxSize; arr = new int[maxSize]; //指向队列前一个位置 front = -1;//头指针 rear = -1; //尾指针 } //判断队列是否满 public boolean isFull() { if(rear == maxSize-1) return true; else return false; } //判断队列是否为空 public boolean isEmpty() { if(front == rear) return true; else return false; } //入队 public void addQueue(int n) { //判断是否已满 if(isFull() == true) { System.out.println("队列已满"); return; } rear++; arr[rear] = n; } //出队 public int getQueue() { //判断队列是否为空 if(isEmpty() == true) { System.out.println("队列为空"); return -1; } front++; return arr[front]; } //显示队列的所有数据 public void showQueue(){ if(isEmpty() == true) { System.out.println("队列为空"); return; } for(int i = front+1;i <= rear;i++) { System.out.println(arr[i]); } } }
结果:
true
3
-------------
3
5
7
3
true