1 队列简介
1.1 队列是一种特殊的线性表,它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作。进行插入操作的端称为队尾,进行删除操作的端称为队头。
1.2 在队列中插入一个队列元素称为入队,从队列中删除一个队列元素称为出队。因为队列只允许在一端插入,在另一端删除,所以只有最早进入队列的元素才能最先从队列中删除,故队列又称为先进先出线性表。
1.3 队列分为:
1.3.1 单向队列:只能在一端插入数据,另一端删除数据。
1.3.2 双向队列:每一端都可以进行插入数据和删除数据操作。
2 数组实现单向队列
2.1 代码示例
package com.example.array;
/**
* 数组实现单向队列
*/
public class Queue {
/**
* 保存队列元素的数组
*/
private int[] queueArray;
/**
* 队列最大元素容量
*/
private int maxSize;
/**
* 队头下标
*/
private int front;
/**
* 队尾下标
*/
private int rear;
/**
* 队列实际元素数量
*/
private int actualSize;
public Queue(int maxSize) {
this.maxSize = maxSize;
this.queueArray = new int[maxSize];
this.front = 0;
this.rear = -1;
this.actualSize = 0;
}
/**
* 入队
* @param value
*/
public void insert(int value) {
if (isFull()) {
throw new RuntimeException("队列已满!");
} else {
if (rear == maxSize - 1) {
rear = -1;
}
queueArray[++rear] = value;
actualSize++;
}
}
/**
* 出队
* @return
*/
public int remove() {
if (isEmpty()) {
throw new RuntimeException("队列为空!");
} else {
int removeValue = queueArray[front];
queueArray[front] = -1;
front++;
if (front == maxSize) {
front = 0;
}
actualSize--;
return removeValue;
}
}
/**
* 查看对头元素
* @return
*/
public int peek() {
if (isEmpty()) {
throw new RuntimeException("队列为空!");
}
return queueArray[front];
}
/**
* 判断队列是否已满
* @return
*/
public boolean isFull() {
return actualSize == maxSize;
}
/**
* 判断队列是否为空
* @return
*/
public boolean isEmpty() {
return actualSize == 0;
}
/**
* 获取队列实际元素数量
* @return
*/
public int getSize() {
return actualSize;
}
}
2.2 测试
package com.example.array;
import org.junit.Test;
/**
* 测试数组实现单向队列
*/
public class TestQueue {
@Test
public void testQueue() {
Queue myQueue = new Queue(3);
// System.out.println("peek:" + myQueue.peek());
myQueue.insert(1);
myQueue.insert(2);
myQueue.insert(3);
System.out.println("size:" + myQueue.getSize());
System.out.println("peek:" + myQueue.peek());
System.out.println("size:" + myQueue.getSize());
int removeValue = myQueue.remove();
System.out.println("removeValue:" + removeValue);
System.out.println("size:" + myQueue.getSize());
System.out.println("peek:" + myQueue.peek());
myQueue.insert(4);
System.out.println("size:" + myQueue.getSize());
myQueue.insert(5);
System.out.println("size:" + myQueue.getSize());
}
}