队列
队列
概念:队列是一个有序列表,可以使用数组或链表来实现,必须满足先入先出的原则
应用
利用数组模拟队列

分析思路
利用数组来模拟队列,其数组声明包括4个变量;数组的大小Maxsize,双指针:first;rear 表示队列前后端 ;一个数组arr用来存储数据。
当我们操作数组时,需要判断数组是否为空,当数组为空时,我们就取不了数据,判断条件为first=rear;还需要判断数组是否为满,若数组为满,则添加不了数据。判断条件为:rear=Maxsize-1;
当添加数据时,rear++;往后移动一位,将值添加上;当取值时first;first向后移动一位,取出此时first值。
注意:first指向队列头部,分析出first时指向队列头的前一个位置。
rear指向队列的最后一个元素。
package 队列;
import java.sql.SQLOutput;
import java.util.Scanner;
public class 数组模拟队列 {
public static void main(String[] args) {
//创建队列
Quene Q = new Quene(3);
char key = ' ';//用于接收用户输入
Scanner sc = new Scanner(System.in);
boolean loop = true;
//输出一个菜单
while (loop) {
System.out.println("s:显示队列");
System.out.println("e:退出程序");
System.out.println("a:添加数据");
System.out.println("g:取去数据");
System.out.println("h:查看头数据");
key = sc.next().charAt(0);//接受键盘的字符
switch (key) {
case 's':
Q.show();
break;
case 'a':
System.out.println("请输入一个数");
int value = sc.nextInt();
Q.add(value);
break;
case 'g':
try {
int res = Q.out();
System.out.println("取出的数据是:" + res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int res = Q.head();
System.out.println("头数据为:" + res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
sc.close();
loop = false;
break;
default:
break;
}
}
System.out.println("程序退出");
}
}
class Quene {
//定义队列成员变量
public int Maxsize;
public int first;
public int rear;
public int[] arr;
//定义构造方法
public Quene() {
}
public Quene(int maxsize) {
Maxsize = maxsize;
arr = new int[Maxsize];
first = -1;
rear = -1;
}
//成员方法
//判断队列是否为空
public boolean isempty() {
return first == rear;
}
//判断队列是否为满
public boolean isfull() {
return rear == Maxsize - 1;
}
//向队列中添加数据
public void add(int n){
//判断队列是否未满,若满则不能添加数据
if(isfull()){
System.out.println("队列满,无法添加");
return;
}
rear++;
arr[rear]=n;
}
//获取队列数据;出队列
public int out(){
//判断队列是否为空,若为空,则抛出异常
if(isempty()){
throw new RuntimeException("队列空,不可以出列");
}
first++;
return arr[first];
}
//显示队列所有数据
public void show(){
if(isempty()){
System.out.println("队列为空");
return;//这个地方的return一定不要丢
}
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
//显示队列头数据
public int head(){
if (isempty()){
throw new RuntimeException("队列空,无数据");
}
return arr[first+1];
}
}

浙公网安备 33010602011771号