数组模拟队列
- 通过front和rear控制队列的头部和尾部
- 缺点:每次变更队列,需创建新的数组来装数据
package com.zsx.structure.queue;
public class ArrayQueueDemo {
public static void main(String[] args) {
//初始化队列
ArrayQueue arrayQueue = new ArrayQueue(3);
//队列添加数据
arrayQueue.addQueue(11);
arrayQueue.addQueue(22);
arrayQueue.addQueue(33);
//显示队列
arrayQueue.show();
//从队列中取出头部
arrayQueue.getQueue();
//显示队列数据
arrayQueue.show();
//显示头部数据而不取
System.out.println(arrayQueue.peek());
//显示队列数据
arrayQueue.show();
//从队列中取出头部
arrayQueue.getQueue();
//显示队列数据
arrayQueue.show();
}
}
//数组模拟一个队列
class ArrayQueue {
//队列的容量
private int maxSize;
//头部指针
private int front;
//尾部指针
private int rear;
//队列-数据
private int[] arr;
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
arr = new int[this.maxSize];
front = -1;
rear = -1;
}
/**
* 添加数据到队列
*
* @param data
*/
public void addQueue(int data) {
if (isFull()) {
throw new RuntimeException("队列满了");
}
//尾部指针后移
rear++;
//添加数据
arr[rear] = data;
}
/**
* 获取队列的数据
*/
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
//头部指针后移
front++;
//取出对应的值
int data = arr[front];
System.out.println("取出头部:" + data);
//队列移除该数据
int[] arr1 = new int[this.maxSize];
int count = 0;
for (int i = front; i < rear; i++) {
arr1[count++] = arr[i];
}
arr = arr1;
front--;
rear--;
return data;
}
/**
* 显示头部数据
*
* @return
*/
public int peek() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
return arr[0];
}
/**
* 显示队列的数据
*/
public void show() {
System.out.println("=======队列数据=========");
System.out.println("最大长度为:" + this.maxSize);
for (int i = 0; i <= rear; i++) {
System.out.println("arr[" + i + "]:" + arr[i]);
}
}
/**
* 判断队列为满
*
* @return
*/
public boolean isFull() {
return rear == maxSize - 1;
}
/**
* 判断队列为空
*
* @return
*/
public boolean isEmpty() {
return rear == front;
}
}
结果: