主要思想是:
1.创建队列头部指针。
2.创建队列尾部指针。
3.创建数组。
入队是尾部指针增加,数组赋值。
出队时头部指针增加,数组拿值。
package shuJuJieGouYuSuanFa;
import java.util.LinkedList;
import java.util.Queue;
/**
* @ClassName ArrayAueue
* @Author 瞿肖
* @Date 2022/7/12 19:34
*/
public class ArrayAueue {
public static void main(String[] args) {
QueueMy q = new QueueMy(8);
q.offer(1);
q.offer(2);
q.offer(3);
q.offer(4);
q.offer(5);
q.offer(6);
q.offer(7);
System.out.println(q.poll());
System.out.println(q.poll());
System.out.println(q.showQueue());
}
static class QueueMy {
// 最大值
private int maxSize;
//队列头 //front==top
private int top;
//队列尾
private int end;
//底层数组
private int[] arr;
public QueueMy(int max) {
maxSize = max;
arr = new int[maxSize];
//-1:指向头部的前一位
top = -1;
end = -1;
}
//队列是否已满
public boolean isFull() {
return end == maxSize - 1;
}
//队列是否为空
public boolean isEmpty() {
return end == top;
}
//添加到尾部
public boolean offer(int data) {
boolean f = false;
if (isFull()) {
throw new RuntimeException("已满!");
} else {
f = true;
arr[++end] = data;
}
return f;
}
//获取头部数据、并且删除头部
public int poll() {
if (isEmpty()) {
throw new RuntimeException("队列为空!");
}
return arr[++top];
}
//查看头部值,不删除
public int peek() {
if (isEmpty()) {
throw new RuntimeException("头部为空");
}
return arr[top + 1];
}
//获取当前队列所有值
public String showQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空!");
}
int top1 = top;
int end1 = end;
int[] arr1 = arr;
StringBuffer s = new StringBuffer();
s = s.append("[" + arr1[++top1]);
for (int i = 2; i <= (end - top); i++) {
s = s.append("," + arr1[++top1]);
}
s = s.append("]");
return "" + s;
}
}
}