普通队列
1.介绍
1)队列是一个有序列表,可以用数组或是链表来实现。
2)遵循先入先出的原则。即:先存入队列的数据,要先取出。后存入的要后取出
举例
我们在车站排队取票就是一种队列,排在前面的先取到票,排在后面的后取到票
2.数组模拟队列
思路
- 队列本身是有序列表,若使用数组的结构来存储队列的数据,则队列数组的声明如下图,其中maxSize是该队列的最大容量。
- 因为队列的输出、输入是分别从前后端来处理,因此需要两个变量front及rear分别记录队列前后端的下标,front 会随着数据输出而改变,而rear则是随着数据输入而改变,如图所示:

- 往队列添加数据
1)判断队列是否满,如果满了则不能添加
2)尾指针往后移一个位置:rear+1 arr[rear] = n
- 从队列取出数据
1)判断队列是否为空
2)front往后移动一个位置:front+1
实现
public class ArrayQueue{
private int maxSize; //数组的最大容量
private int rear; //队列尾
private int front; //队列头
private int[] arr; //用于存放数据,模拟队列
//初始化队列
public ArrayQueue(int maxSize){
this.maxSize = maxSize;
arr = new int[maxSize];
rear = -1;
front = -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()){
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]=%d\n",i,arr[i]);
}
}
//显示队头数据
public int showQueueHead(){
//判断是否为空
if(isEmpty()){
throw new RuntimeException("队列为空,没有数据可显示");
}
return arr[front+1];
}
}
测试
public static void main(String[] args) {
ArrayQueue queue = new ArrayQueue(4);
boolean loop = true;
char key = ' '; //接受用户输入
Scanner sc = new Scanner(System.in);
while(loop){
System.out.println("s(show)显示队列");
System.out.println("g(get)从队列取出数据");
System.out.println("a(add)添加数据");
System.out.println("h(Head)显示队列头数据");
System.out.println("e(exit)");
key = sc.next().charAt(0); //接收一个字符串
switch (key){
case 's':
queue.showQueue();
break;
case 'g':
try {
int value = queue.getQueue();
System.out.printf("取出的数据为%d\n",value);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'a':
System.out.println("输入你要添加的数");
int val = sc.nextInt();
queue.addQueue(val);
break;
case 'h':
try {
int value = queue.showQueueHead();
System.out.printf("队列头部的数据为%d\n",value);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'e':
sc.close();
loop = false;
break;
default:
break;
}
}
}
浙公网安备 33010602011771号