数组模拟队列(一)
数组使用一次不能复用
package com.wmq.atguigu.queue;
import java.util.Scanner;
/**
* 数组模拟队列
*/
public class ArrayQueueDemo {
public static void main(String[] args) {
ArrayQueue queue = new ArrayQueue(3);
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while (loop){
char key = scanner.next().charAt(0);
switch(key){
case 's':
queue.showQueue();
break;
case 'a':
System.out.println("输入一个数");
queue.addQueue(scanner.nextInt());
break;
case 'p':
try {
int i = queue.printQueue();
System.out.println("取出的数据为:"+i);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'h':
try {
System.out.println("头数据为:"+queue.headQueue());
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'q':
scanner.close();
loop=false;
break;
default:
break;
}
}
System.out.println("程序退出");
}
}
class ArrayQueue{
private int maxSize;
private int font;
private int rear;
private int[] arr;
public ArrayQueue(int arrMaxSize){
font = -1;
rear = -1;
maxSize = arrMaxSize;
arr = new int[maxSize];
}
//判断队列是否满
public boolean isFull(){
return rear == maxSize-1;
}
//判断队列是否为空
public boolean isEmpty(){
return rear == font;
}
//向队列加入数据
public void addQueue(int n){
if (isFull()){
System.out.println("队列已满");
return;
}else{
rear++;
arr[rear] = n;
}
}
//输出队列中的数据
public int printQueue(){
if (isEmpty()){
throw new RuntimeException("队列为空");
}else{
font++;
return arr[font];
}
}
//显示队列中的数据
public void showQueue(){
if (isEmpty()){
System.out.println("队列为空");
return;
}else{
for (int i = 0; i < arr.length; i++) {
System.out.printf("arr[%d]=%d\n",i,arr[i]);
}
}
}
//显示队列的头数据
public int headQueue(){
if (isEmpty()){
throw new RuntimeException("队列为空");
}else{
return arr[font+1];
}
}
}