队列
介绍
- 队列是一个 有序列表,可以用 数组或是 链表来实现。
- 遵循 先入先出的原则。
数组模拟队列图
数组模拟队列思路(环形队列)
1.队列本身是有序列表,若使用数组的结构来存储队列的数据,则队列数组的声明如下图, 其中 maxSize 是该队
列的最大容量。
2.因为队列的输出、输入是分别从前后端来处理,因此需要两个变量 front 及 rear 分别记录队列前后端的下标,
front 会随着数据输出而改变,而 rear 则是随着数据输入而改变
代码实现
class Queue{
private int maxSize; //队列最大容量
private int front; //队首,指向队首元素
private int rear; //队尾,指向队列最后一个元素的后一位
private int[] arr; //保存数据
public Queue(){
maxSize = 4;
arr = new int[maxSize];
}
public Queue(int maxSize){
//此处加1是因为rear指向的位置要保持为空,因为它总是指向队尾最后一个元素的下一个位置,
this.maxSize = maxSize+1;
arr = new int[maxSize];
}
/**
* 入队操作
*/
public void push(int element){
if(isFull()){
System.out.println("队列已满");
return;
}
arr[rear] = element;
rear = (rear + 1) % maxSize;
}
/**
*出队操作
*/
public int pop() throws RuntimeException {
if(isEmpty()){
throw new RuntimeException("队列为空");
}
int element = arr[front];
front = (front + 1) % maxSize;
return element;
}
/**
* 获取当前元素个数
*
*/
public int size(){
return (rear - front + maxSize) % maxSize;
}
/**
* 判空操作
* 单front指针和rear指针指向同一位置时,则为空
*/
public boolean isEmpty(){
return rear == front;
}
/**
* 判满操作
* rear指针再移动一位等于front,说明此时队列已满
*/
public boolean isFull(){
return (rear + 1) % maxSize == front;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
for (int i = front; i < front + this.size(); i++){
if(i != front) sb.append(',');
sb.append(arr[i % maxSize]);
}
return sb.toString();
}
}
public class QueueDemo {
public static void main(String[] args) {
//测试队列
Queue queue = new Queue();
queue.push(3);
queue.push(1);
queue.push(2);
queue.pop();
System.out.println(queue);
}
}
改进版本,使用泛型
class Queuee<E>{
private static final int DEFAULT_MAX_SIZE = 10; //默认的队列最大容量,即数组的长度
private int maxSize;
private int front ; //指向队首的前一个元素
private int rear ; //指向队尾元素
private E[] arr = null; //用于存放队列的数组
public Queuee(Class<E> clazz){
maxSize = DEFAULT_MAX_SIZE;
arr = (E[])Array.newInstance(clazz,DEFAULT_MAX_SIZE);
}
/**
*
* @param clazz 要实例化对象数组的具体类型
* @param initCapacity 初始化的最大容量
*/
public Queuee(Class<E> clazz,int initCapacity){
if(initCapacity <= 0) throw new RuntimeException("创建队列失败");
maxSize = initCapacity+1;
arr =(E[]) Array.newInstance(clazz,initCapacity+1);
}
/**
* 入队
*/
public void push(E element){
if(isFull()){
System.out.println("Queue has full.");
return;
}
arr[rear] = element;
rear = (rear+1) % maxSize;
}
/**
* 出队
*/
public E pop(){
if(isEmpty()){
throw new RuntimeException("Queue is empty");
}
E element = arr[front];
front = (front + 1) % maxSize;
return element;
}
/**
* 获取当前元素个数
*
*/
public int size(){
return (rear - front + maxSize) % maxSize;
}
/**
* 判空操作
*
*/
public boolean isEmpty(){
return rear == front;
}
/**
* 判满操作
*/
public boolean isFull(){
return (rear + 1) % maxSize == front;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
for (int i = front; i < front + this.size(); i++){
if(i != front) sb.append(',');
sb.append(arr[i % maxSize]);
}
return sb.toString();
}
}