java实现环形队列
Posted selfup
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java实现环形队列相关的知识,希望对你有一定的参考价值。
环形队列
- 队列是一种先进先出的数据结构
代码思路
- 用数组存放队列的数据
- front指向队首元素
- rear指向队尾元素
- num存放当前已经存在的元素个数,有了num,判断队列是否为空是否存满比较方便
public class Demo2 {
public static void main(String[] args) {
ArrayQueue queue = new ArrayQueue(5);
queue.addNum(10001);
queue.addNum(10002);
queue.addNum(10003);
queue.addNum(10004);
queue.addNum(10005);
System.out.println(queue.getNum());
System.out.println(queue.getNum());
queue.addNum(1);
queue.addNum(2);
queue.addNum(3);
queue.showQueue();
System.out.println(queue.getNum());
System.out.println(queue.getNum());
System.out.println(queue.getNum());
System.out.println(queue.getNum());
System.out.println(queue.getNum());
System.out.println(queue.getNum());
}
}
class ArrayQueue {
//队列的大小
int maxSize;
//用数组来实现队列
int[] arr;
//指向队列首元素
int front;
//指向队列尾元素
int rear;
//当前队列的元素的个数
int num;
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
this.arr = new int[this.maxSize];
front = -1;
rear = -1;
}
public boolean isFull() {
return num == maxSize;
}
public boolean isEmpty() {
return num == 0;
}
public void addNum(int num) {
if (isFull()) {
System.out.println("队列已满,无法在进行入队操作");
return;
}
//队尾标记后移,指向要放入的元素的位置
if (front == -1 && rear == -1) {
front = 0;
rear = 0;
} else {
rear = rear + 1;
}
if (rear == maxSize) {
rear = 0;
}
arr[rear] = num;
this.num++;
}
public int getNum() {
if (isEmpty()) {
throw new RuntimeException("队列为空,无法出队");
}
//队首标记后移,指向队首元素
System.out.print("出队元素是:");
this.num--;
int res = arr[front];
front++;
if (front == maxSize) {
front = 0;
}
return res;
}
public void showQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空,无法遍历");
}
System.out.println("遍历队列");
if (rear >= front) {
for (int start = front; start <= rear; start++) {
System.out.println(arr[start]);
}
} else {
for (int start = front; start <= maxSize - 1; start++) {
System.out.println(arr[start]);
}
for (int start = 0; start <= rear; start++) {
System.out.println(arr[start]);
}
}
}
}
以上是关于java实现环形队列的主要内容,如果未能解决你的问题,请参考以下文章