队列是一个基本的数据结构。他的原理是先进先出FIFO 可以通过数据或者链表对其进行实现
package com.zy.queue;
public 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() {
if (rear == maxSize - 1) {
return true;
}else
return false;
}
//判断队列是否为空
public boolean isEmpty() {
if(rear == front) {
return true;
}else
return false;
}
//进队列
public boolean addQueue(int n) {
//判断队列是否已满
if(isFull()) {
throw new RuntimeException("队列已满无法添加数据");
}
//添加数据
arr[++rear] = n;
return true;
}
//出队列
public int outQueue() {
//判断队列是否为空
if(isEmpty()) {
throw new RuntimeException("当前队列为空");
}
return arr[++front];
}
//显示队列信息
public void showQueue() {
if(isEmpty()) {
throw new RuntimeException("当前队列为空");
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
}
}
通过数组实现循环队列
package com.zy.queue;
public class ArrayQueue1 {
// 循环队列的数组实现
private int maxSize;
private int front;
private int rear;
private int[] arr;
// 初始化
public ArrayQueue1(int maxSize) {
this.maxSize = maxSize;
front = 0;
rear = 0;
arr = new int[maxSize];
}
// 判断满
public boolean isFull() {
if ((rear + 1) % maxSize == front) {
return true;
} else
return false;
}
// 判断为空
public boolean isEmpty() {
return rear == front;
}
// 元素进栈
public boolean addQueue(int n) {
if (isFull())
throw new RuntimeException("队列满了无法添加");
arr[rear] = n;
rear = (rear + 1) % maxSize;
return true;
}
// 元素出栈
public int outQueue() {
if (isEmpty())
throw new RuntimeException("队列为空");
int val = arr[front];
front = (front + 1) % maxSize;
return val;
}
public int arrLen() {
return (rear - front + maxSize) % maxSize;
}
// 显示队列元素
public void showQueue() {
if (isEmpty())
throw new RuntimeException("当前队列为空");
int len = arrLen();
for (int i = front; i < front + len; i++) {
System.out.println(arr[i % maxSize]);
}
}
}