概念
1.队列是一个有序的列表,可以使用数组和链表实现
2.队列是先入先出的模式(FIFO)
一次性的队列(使用数组表示)
思路分析
1.需要两个变量来表示队列前后端处理位置head表示队列头,tail表示队列尾
2.当加入元素时,判断队列是否为空,即head==tail,不为空就将tail后移;tail==maxSize-1 表时队列已满
3.初始化head=-1;head为指向队列头的前一个位置;tail=-1;tail表示队列的最后一个数据
Java代码
class ArrayQueue {
private int maxSize;
private int head;
private int tail;
private int[] array;
public ArrayQueue(int size) {
this.maxSize = size;
array = new int[maxSize];
head = -1;//head为当前队列第一个元素的上一个位置
tail = -1;//tail为当前队列的最后一个元素所在位置
}
public boolean isFull() {
return tail == maxSize - 1;
}
public boolean isEmpty() {
return head == tail;
}
public void addQueue(int value) {
if (isFull()) {
throw new RuntimeException("队列满了");
}
tail++;
array[tail] = value;
}
public int deQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
head++;
return array[head];
}
public int headQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
return array[head + 1];
}
public void display() {
if (isEmpty()) {
System.out.println("队列为空");
return;
}
for (int i = head + 1; i < maxSize; i++) {
System.out.print(array[i] + "\t");
}
}
}
循环队列
避免假溢出问题
实现思路(取模操作实现环形队列)
1.head指向队列的第一个位置,当有出队操作,则head移向下一个位置
2.tail指向队列最后一个元素的后一个位置,例如一个maxSize=5的队列
当tail=5 取模后tail%5=0,此时认为队列已满,但是和判断队列为空head==tail条件重复(0%5=0),无法判断
由此舍弃一个节点位,使用tail+1判断下一个元素插入后,是否还能再加入元素
如果不能说明队列满了,但是其实还剩余一个位置
3.判断为空head==tail
4.判断已满(tail+1)%maxSize==head
Java代码
class CycleQueue {
private int maxSize;
private int head;//head指向队列的第一个元素
private int tail;//tail指向整个队列的最后一个元素的后一个位置
private int[] array;
public CycleQueue(int size) {
this.maxSize = size;
array = new int[maxSize];
}
public boolean isFull() {
return (tail + 1) % maxSize == head;
}
public boolean isEmpty() {
return head == tail;
}
public void addQueue(int value) {
if (isFull()) {
throw new RuntimeException("队列满了");
}
array[tail] = value;
tail = (tail + 1) % maxSize;
}
public int deQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
int tmp = array[head];
head = (head + 1) % maxSize;
return tmp;
}
public int getSize() {
return (tail - head) % maxSize;
}
public void display() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
for (int i = head; i < head + getSize(); i++) {
System.out.printf("array[%d]=%d\t", i % maxSize, array[i % maxSize]);
}
}
}