概述
- 队列是一个有序列表
- 遵循先入先出的原则
用数组模拟数据
class ArrayQueue {
private int maxSize;
private int front;
private int rear;
private int[] arr;
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
this.arr = new int[maxSize];
front = -1;
rear = -1;
}
public boolean isFull() {
return rear == maxSize - 1;
}
public boolean isEmpty() {
return front == rear;
}
public void addQueue(int n) {
if(isFull()) {
System.out.println("队列满");
return;
}
rear++;
arr[rear] = n;
}
public int getQueue() {
if(isEmpty()) {
throw new RuntimeException("队列空");
}
front++;
return arr[front];
}
public void showQueue() {
if(isEmpty()) {
throw new RuntimeException("队列空");
}
for(int elem : arr) {
System.out.println(elem);
}
}
public int headQueue() {
if(isEmpty()) {
throw new RuntimeException("队列空");
}
return arr[++front];
}
}
数组模拟环形队列
思路
- front指向队列的第一个元素,也就是说arr[front]就是队列的第一个元素front的初始值=0
- rear指向队列的最后一个元素的后一个位置,因为空出一个空间作为约定,rear初始值=0
- 当队列满时,条件是(rear + 1)%maxsize=front
- 队列为空时,rear==front
- 队列中有效的数据的个数(rear+maxsize-front)%maxsize
class CircleArray{
private int maxSize;
private int front = 0;
private int rear = 0;
private int[] arr;
public CircleArray(int maxSize){
this.maxSize = maxSize;
this.arr = new int[maxSize];
}
public boolean isFull(){
return (rear + 1) % maxSize == front;
}
public boolean isEmpty(){
return front == rear;
}
public void addQueue(int n){
if(isFull()){
System.out.println("队列已满");
return;
}
arr[rear] = n;
rear = (rear + 1) % maxSize;
}
public int getQueue(){
if(isEmpty()){
System.out.println("队列已空");
}
int value = arr[front];
front = (front + 1) % maxSize;
return value;
}
public void showQueue(){
if(isEmpty()){
System.out.println("队列为空");
}
for(int i = front ; i < front + size() ; i++){
System.out.printf("arr[%d] = %d\n" , i % maxSize ,arr[i % maxSize]);
}
}
public int headQueue(){
if(isEmpty()){
System.out.println("队列为空");
}
return arr[front];
}
public int size(){
return (rear + maxSize - front) % maxSize;
}
}