- 队列的特点:
front会随着数据的输出二改变,rear会随着数据输入而改变。
package com.chanchan.queue;
import java.util.Scanner;
public class Queue01 {
public static void main(String[] args){
//模拟队列
queueArray array = new queueArray( 3 );
//接受用户输入
char key=' ';
Scanner scanner = new Scanner(System.in);
boolean loop=true;
//输出一个菜单
while (loop){
System.out.println("s(show):显示队列");
System.out.println("e(exit):推出程序");
System.out.println("a(add):添加数据队列");
System.out.println("g(get):从队列取出数据");
System.out.println("h(head):查看队列头数据元素");
key=scanner.next().charAt( 0 );//接受一个字符
switch (key){
case 's':
array.show();
break;
case 'a':
System.out.println("输入一个值:");
int value=scanner.nextInt();
array.addQueue( value );
break;
case 'g':
try {
int res=array.getQueue();
System.out.println("取出的数据是:"+res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
System.out.println("查看队列头数据元素:"+array.headQueue());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e': //退出整个程序
scanner.close();
loop=false;
break;
}
}
System.out.println("程序退出");
}
}
//用数组模拟队列
class queueArray {
private int maxSize; //定义数组的最大长度,但是只能存两个数据,是因为要预留一个空间。
private int front; //定义队列的头指针
private int rear; //定义队列的尾指针
int arr[]; //定义一个数组,模拟队列
public queueArray(int max){ //构造函数初始化
maxSize=max;
arr=new int[maxSize]; //初始化数组
front=-1;
rear=-1; //初始化指针,让指针指向前一个元素。
}
//定义队列的方法
//判断队列是否已满;
public boolean isFull(){
return rear==maxSize-1;
}
//判断队列是为空
public boolean isEmpty(){
return rear==front;
}
//给队列添加一个元素:入队
public void addQueue(int x){
if(isFull()){
System.out.println("队列已满不能加入元素");
}else {
rear++;
arr[rear]=x;
}
return;
}
//获得队列的元素:出队
public int getQueue() throws Exception {
if(isEmpty()){
//通过抛出异常
throw new Exception("队列为空,不能取数据"); //throw本身会使我们的代码return,不需要再return;
}
front++; //front指向队列的前一个元素。
return arr[front];
}
//显示队列的全部元素,遍历数组;
public void show(){
if(isEmpty()){
System.out.println("队列为空");
return;
}
for(int i=0;i< arr.length;i++){
System.out.printf("arr[%d]=%d",i,arr[i]);//遍历数组元素。
}
}
//显示队列的头数据是谁
public int headQueue() throws Exception {
if(isEmpty()){
throw new Exception("队列为空");
}
return arr[front+1];
}
}
问题分析并优化:
(1)目前数组使用一次就不能再使用,没有达到复用的效果,
(2)将这个数组使用算法,改进成一个环形的数组,用取模的方法。