标签:队列 empty bsp else maxsize java bool ++ ==
采用循环队列时,队列中共有元素:(rear+maxSize-front)%maxSize
ArrayQueue1.java
public 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 = 0;//头指针 rear = 0; //尾指针 } //判断队列是否满 public boolean isFull() { if((rear+1)%maxSize == front) 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; } arr[rear] = n; rear = (rear+1) % maxSize ; } //出队 public int getQueue() { //判断队列是否为空 if(isEmpty() == true) { System.out.println("队列为空"); return -1; } int x = arr[front]; front = (front+1) % maxSize; return x; } //显示队列的所有数据 public void showQueue(){ if(isEmpty() == true) { System.out.println("队列为空"); return; } for(int i = front; i < front+size(); i++) { System.out.println(arr[(i%maxSize)]); } } public int size() { return (rear+maxSize-front)%maxSize; } }
test.java
public class test{ public static void main(String[] args) { //创建一个队列 ArrayQueue1 a = new ArrayQueue1(); a.creatArrayQueue(6); 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.addQueue(2); a.showQueue(); System.out.println(a.isFull());//此时虽然队列中的有效数字只有4个,不到5个,但是rear指针已经移到了maxSize-1的位置了。 } }
输出:
true 3 ------------- 3 5 7 3 2 true
结果图示:
标签:队列 empty bsp else maxsize java bool ++ ==
原文地址:https://www.cnblogs.com/lintianxiajun/p/12826582.html