java中的队列
常见的数据结构:https://blog.csdn.net/weixin_43304253/article/details/119764275
- 先进先出
入队enqueue(),放一个数据到队列尾部;出队:dequeue();从队列头部取出一个元素
代码实现
package com.zheng.demo5;
public class MyQueue {
public static void main(String[] args) {
ArrayQueue queue = new ArrayQueue(6);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
System.out.println("遍历队列");
queue.list();
System.out.println("出队列两个数据:");
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
System.out.println("出队列后");
queue.list();
}
}
class ArrayQueue {
private int first;//队列头
private int last;//队列尾
private int sizeMax;//队列大小
private int[] queue;//队列
//构造函数初始化
public ArrayQueue(int sizeMax) {
this.sizeMax = sizeMax;
queue = new int[this.sizeMax];
first = this.sizeMax - 1;//将队列头和尾初始值为队列的最前端
last = this.sizeMax - 1;
}
//判断队列是否满
public boolean isFull() {
return last == -1;//代表插入的数据满
}
//判断是否为空
public boolean isEmpty() {
return first == last;//当队列头和队列尾相同的情况下
}
//入队列
public void enqueue(int data) {
//判断队列是否满
if (isFull()) {
throw new RuntimeException("队列满");
}
queue[last] = data;
last--;
}
//出队列
public int dequeue() {
//判断队列是否为空
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
int val = queue[first];
first--;
return val;
}
//遍历
public void list() {
//判断队列是否为空
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
for (int i = first; i > last; i--) {
System.out.printf("queue[%d]=%d\n", i, queue[i]);
}
}
}