数组实现队列(Java)(文末附代码)
本章所实现的队列存在缺陷(空间不可以重复使用)
本章目的是为了展现队列的先进先出的特点
循环队列在这:数组实现循环队列-Java版本
- 队列图示
- 解释
1.head表示队列头部下标,默认值为-1
2.tail表示队列尾部下标,默认值为-1
3.入队:先将tail下标后移一位,再将入队元素赋值于arr[tail];
4.出队:先将head下标后移一位,再将当前head上元素元素弹出arr[head];
5.判断队空:head=tail 时对空
6.判断队满:MaxSize = tail+1;
队列接口.java
package study.data.queue;
public interface MyQueue {
/**
* 补充接口小知识:
* 1.接口中的方法会被隐式的指定为 public abstract (只能是 public abstract,其他修饰符都会报错)。
* 2.接口中的变量会被隐式的指定为 public static final 变量(并且只能是 public,用 private 修饰会报编译错误。)
* @param i
*/
// 判断队列是否为空
boolean isEmpty();
// 判断队列是否满了
boolean isFull();
// 添加
void addQueue(int i);
// 取出元素
int getQueue();
// 遍历队列
void printQueue();
// 获取第一个元素
void headQueue();
}
Bug队列.java
package study.data.queue;
public class MyBugQueue implements MyQueue {
protected int maxSize;
protected int head;
protected int tail;
protected int[] arr;
public MyBugQueue(int size) {
this.maxSize = size;
this.head = -1;// 队列头部下标
this.tail = -1;// 队列尾部下标
this.arr = new int[this.maxSize];
}
@Override
public boolean isEmpty() {
return tail == head;
}
@Override
public boolean isFull() {
// 如果队列尾等于MaxSize - 1 则队列满
// 若队列MaxSize 为 6 ; 此时tail = 5 则tail在队列的最后一个下标上 ;所以判定队列满
return tail == (maxSize-1);
}
@Override
public void addQueue(int i) {
// 如果满了
if (isFull()){
System.out.println("队列已满");
return;
}
// 如果没满,下标先向后移动1 移动到要添加的位置上 再赋值
tail = tail+1;
arr[tail]=i;
}
@Override
public int getQueue(){
if (isEmpty()){
throw new RuntimeException("队列为空");
}
// 先将下标移动到要取得值上
head = head+1;
return arr[head];
}
@Override
public void printQueue() {
// if(isEmpty()){
// throw new RuntimeException("队列为空");
// }
System.out.print("队列为:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.print("下标为:");
for (int i = 0; i < arr.length; i++) {
System.out.print(i+" ");
}
System.out.println();
}
@Override
public void headQueue() {
if (isEmpty()){
throw new RuntimeException("队列为空");
}
System.out.println(arr[head + 1]);
}
}
测试类
package study.data.queue;
import java.util.Scanner;
public class QueueTest {
public static void main(String[] args) {
MyQueue queue = new MyBugQueue(3);
Scanner scanner = new Scanner(System.in);
boolean flag = true;
char input ;
while (flag){
System.out.println("入队(a)");
System.out.println("出队(g)");
System.out.println("遍历(s)");
System.out.println("偷看(h)");
input = scanner.next().charAt(0);
switch (input){
case 'a':
System.out.print("请输入一个数:");
queue.addQueue(scanner.nextInt());
break;
case 'g':
System.out.println("出队元素为:"+queue.getQueue());
break;
case 's':
queue.printQueue();
break;
case 'h':
queue.headQueue();
break;
default:
break;
}
}
}
}