rear:指向队列中的最后一个元素的后一个位置(空出一个空间) 初始值rear=0
front:指向队列中的第一个元素 初始值 front=0
数组arr[]大小为maxSize
队列满条件:(rear+1)%maxSize=front
队列空条件:rear==front
队列中有效的数据个数 (rear+MaxSize-front)%maxSize
假设不空出一个空间的话,队列满的条件为:rear%maxSize=front 当队列空时也满足此条件,故无法判断队列是空还是满,这里空一个空间做标记。(也可采用其他标记法)
代码
public class ArrayQueueDemo {
public static void main(String[] args) {
ArrayQueue queue = new ArrayQueue(3);
char key = ' ';//接受用户输入
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while (loop) {
System.out.println("s(show):显示队列");
System.out.println("e(exit):退出程序");
System.out.println("a(add):添加数据到队列");
System.out.println("g(get):从队列取出数据");
System.out.println("h(head):查看队列头的数据");
key = scanner.next().charAt(0);
switch (key) {
case 's':
queue.showQueue();
break;
case 'e':
scanner.close();
loop = false;
break;
case 'a':
System.out.println("输出一个数");
int value = scanner.nextInt();
queue.addQueue(value);
break;
case 'g':
try {
int res = queue.getQueue();
System.out.printf("取出的数据是%d\n", res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
System.out.println("程序退出");
}
}
class ArrayQueue {
private int maxSize;
private int front;
private int rear;
private int[] arr;
public ArrayQueue(int arrMaxSize) {
maxSize = arrMaxSize;
arr = new int[maxSize];
}
//判断队列是否为空
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
public boolean isEmpty() {
return rear == front;
}
//添加元素
public void addQueue(int n) {
if (isFull()) {
System.out.println("队列满,不能加数据");
return;
}
arr[rear] = n;
rear = (rear + 1) % maxSize;
}
//取出元素
int getQueue() {
if (isEmpty()) {
throw new RuntimeException("队列空");
}
int value = arr[front];
front = (front + 1) % maxSize;
return value;
}
//显示元素
public void showQueue() {
if (isEmpty()) {
System.out.println("队列空的,没有数据");
return;
}
for (int i = front; i < front + size(); i++) {
System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
}
}
public int size() {
return (rear + maxSize - front) % maxSize;
}
public int headQueue() {
if (isEmpty()) {
throw new RuntimeException("队列空的,没有数据");
}
return arr[front];
}
}
韩顺平数据结构与算法笔记