使用数组实现队列
缺点在于无法重复利用空间,可以进行环形队列改进
package com.queue;
import java.util.Scanner;
public class MyArrayQueueDemo {
public static void main(String[] args) {
MyArrayQueue myArrayQueue = new MyArrayQueue(3);
char key=' ';
Scanner in=new Scanner(System.in);
boolean loop=true;
while(loop){
key=in.next().charAt(0);//接受第一个字符
switch(key){
case 's':
myArrayQueue.showQueue();
break;
case 'a':
myArrayQueue.addQueue(in.nextInt());
break;
case 'g':
try{
int res=myArrayQueue.getQueue();
System.out.println("数据是"+res);
}catch (Exception e){
//输出异常信息
System.out.println(e.getMessage());
}
break;
case 'h':
try{
int res=myArrayQueue.headQueue();
System.out.println("队列头"+res);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'e':
in.close();
loop=false;
break;
default:
break;
}
}
}
}
//用数组模拟队列
class MyArrayQueue {
private int maxSize;
private int front;
private int rear;
private int[] arr; //模拟的数组
//队列的构造器
public MyArrayQueue(int arrMaxSize) {
this.maxSize = arrMaxSize;
arr = new int[maxSize];
//注意这里是-1
front = -1;//指向队列头,就是队列头的前一个位置
rear = -1;//指向队列尾的数据(即就是最后一个数据)
}
public boolean isFull() {
return rear == maxSize - 1;
}
public boolean isEmpty() {
return rear == front;
}
public void addQueue(int n) {
if (isFull()) {
System.out.println("满了,别加了");
return;
}
rear++;
arr[rear] = n;
}
public int getQueue() {
if (isEmpty()) {
//抛出异常
//RuntimeException是运行时异常,是Java编译器事先不可预见的异常。
// RuntimeException的子类众多,这里列举一些比较常见的子类:
throw new RuntimeException("空");
}
front++;
return arr[front];
}
public void showQueue() {
if (isEmpty()) {
System.out.println("空的,没有数据");
return;
}
for (int i = 0; i < arr.length; i++) {
System.out.printf("arr[%d]=%dn", i, arr[i]);
}
}
//显示队列头,注意没有取出
public int headQueue() {
if (isEmpty()) {
System.out.println("空的,没有数据");
throw new RuntimeException();
}
//注意这里的操作
return arr[front + 1];
}
}