思路:
约定
- front指向队头的前一个位置
- rear 指向队尾的元素
判断队列满
- rear - front == maxSize;
判断队列空
- rear == front;
入队
- 判断是否队满
- rear++
- arr[rear%maxSize] = data;
出队
- 判断是否队空
- front++ ;
- return arr[front%maxSize];
显示所有数据
for(int i=front+1;i<=rear;i++){
System.out.print(arr[i % maxSize]+" ");
}
防止过度使用队列时,front,rear一直加,导致溢出数据范围,并且要保证同时减,也就是始终保证 尾指针 >= 头指针
if( front > maxSize && rear > maxSize){
front -= maxSize;
rear -= maxSize;
}
数组实现队列基本操作
class ArrayQueue{
private int maxSize;//队列容量
private int front;//指向队头的前一个位置
private int rear;//指向队尾
private int[] arr;//队列数组
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
front = -1;
rear = -1;
}
//判断队列是否满
public boolean isFull() {
return rear == maxSize - 1;
}
//判断队列是否为空
public boolean isEmpty() {
return rear == front;
}
//入队
public boolean add(int data) {
if( isFull() ) {
System.out.println("队列已满,添加失败~");
return false;
}
rear++;//尾指针后移
arr[rear] = data;
return true;
}
//出队
public int pop() {
if( isEmpty() ) {
throw new RuntimeException("队列为空~");
}
front++;//头指针后移
return arr[front];
}
//显示队列所有数据
public void showAll() {
if( isEmpty()) {
System.out.println("队列没有数据!");
return;
}
for(int i=front+1;i<=rear;i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
}
}
操作:
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayQueue arr = new ArrayQueue(4);
boolean loop = true;
while(loop) {
System.out.println("############");
System.out.println("1.入队");
System.out.println("2.出队");
System.out.println("3.显示所有");
System.out.println("0.退出");
int key = scan.nextInt();
switch (key) {
case 1:System.out.println("输入数据:");
int data = scan.nextInt();
arr.add(data);break;
case 2:System.out.println("出队:" + arr.pop());break;
case 3:arr.showAll();break;
case 0:loop=false;break;
default:System.out.println("无效选择");break;
}
}
}
}