1.队列介绍
队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头
2.队列示意图
3.队列特点
- 队列是一个有序列表,可以用数 组和链表来实现
- 队列先进先出,即是先入队列的数据最先被取出,后存入的数据后取出。
4.数组模拟队列场景
5.代码实现:
package queue;
/**
* @author WuChenGuang
* 数组实现队列,插入
*/
public class ArrayQueue {
private final int[] array;
private final int maxSize;
private int frontPoint;
private int rearPoint;
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
array = new int[maxSize];
frontPoint = -1;
rearPoint = -1;
}
/**
* 判断当前队列是否已满
*/
public boolean isFull() {
return rearPoint == maxSize - 1;
}
/**
* 判断是否是空队列
*/
public boolean isEmpty() {
return frontPoint == rearPoint;
}
/**
* 添加元素进入队列
*/
public void add(int n) {
// 判断是否已满
if (isFull()) {
System.out.println("队列已满");
return;
}
rearPoint++;
array[rearPoint] = n;
}
/**
* 获取队列元素并且删除元素,出队列
*/
public int get() {
if (isEmpty()) {
throw new RuntimeException("空队列");
}
frontPoint++;
return array[frontPoint];
}
/**
* 查看队列中的元素
*/
public void findQueue() {
if (isEmpty()) {
throw new RuntimeException("空队列");
}
for (int i = 0; i < array.length; i++) {
System.out.printf("array[%d]=%d\n", i, array[i]);
}
}
/**
* 查看队头元素,不能是出队列
*/
public int frontQueue() {
if (isEmpty()) {
throw new RuntimeException("空队列");
}
return array[frontPoint + 1];
}
}
package queue;
/**
* @author WuChenGuang
*/
public class TestApp {
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(5);
// 向队列中添加元素
arrayQueue.add(1);
arrayQueue.add(2);
arrayQueue.add(3);
arrayQueue.add(4);
arrayQueue.add(5);
// 获取队列元素并且删除元素,出队列
int i = arrayQueue.get();
System.out.println(i);
// 查看队列中所有元素
arrayQueue.findQueue();
}
}
运行结果:
6.链表模拟队列实现:
package queue;
/**
* @author WuChenGuang
*/
public class Node {
/**
* 定义一个头节点
*/
private final static Node head = new Node();
/**
* 下一个结点
*/
Node next;
/**
* 值
*/
int val;
public Node() {
}
private Node(int val) {
this.val = val;
}
/**
* 入队
*/
public void push(int val) {
if (next == null) {
next = new Node(val);
return;
}
Node dummy = next;
while (dummy.next != null) {
dummy = dummy.next;
}
dummy.next = new Node(val);
}
/**
* 出队
*/
public void pop() {
if (next == null) {
System.out.println("空队列");
return;
}
next = next.next;
}
/**
* 打印
*/
public void println() {
Node dummy = next;
if (dummy == null) {
System.out.println("队列为空");
}
while (dummy != null) {
System.out.println(dummy.val);
dummy = dummy.next;
}
}
}
package queue;
/**
* @author WuChenGuang
*/
public class TestNode {
public static void main(String[] args) {
Node node = new Node();
// 添加元素
node.push(1);
node.push(2);
node.push(3);
node.push(4);
node.push(5);
// 显示数据
node.println();
// 弹出元素
node.pop();
System.out.println("弹出元素以后剩余队列:");
node.println();
}
}
运行结果: