队列
- 定义:队列是一种有序的列表。
- 实现形式:可以用数组或者链表实现队列
- 模拟图
- 代码实现
package com.xc.queue;
import java.util.Scanner;
public class ArrayQueue {
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(3);
Scanner scanner = new Scanner(System.in);
while (true){
System.out.println("-------------1-入队--------------");
System.out.println("-------------2-出队--------------");
System.out.println("-------------3-队首元素-----------");
System.out.println("-------------4-显示队列元素--------");
System.out.println("-------------5-退出---------------");
System.out.print("请选择您的操作:");
int choose = scanner.nextInt();
switch (choose){
case 1:
System.out.print("请输入一个元素入队:");
int data = scanner.nextInt();
arrayQueue.offer(data);
System.out.println("当前队列:");
arrayQueue.show();
break;
case 2:
try {
arrayQueue.poll();
System.out.println("当前队列:");
arrayQueue.show();
} catch (Exception e) {
e.printStackTrace();
}
break;
case 3:
System.out.println("当前队列:");
arrayQueue.show();
break;
case 4:
try {
System.out.println(arrayQueue.peek());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 5:
System.exit(0);
}
}
}
private int font;
private int rear;
private int maxSize;
private int [] data;
//初始化队列
public ArrayQueue(int maxSize){
data = new int[maxSize];
this.maxSize = maxSize;
font = -1;
rear = -1;
}
//是否对空
public boolean isEmpty(){
if(font == rear){
return true;
}
return false;
}
//是否队满
public boolean isFull(){
if(rear == maxSize-1){
return true;
}
return false;
}
//入队操作
public void offer(int date){
if(isFull()){
System.out.println("队满无法添加数据");
return ;
}
this.rear ++;
this.data[rear] = date;
}
//出队操作
public int poll() throws Exception {
if(isEmpty()){
System.out.println("对空,出对失败");
throw new Exception("队列为空");
}
int info = this.data[++font];
this.data[font] = 0;
return info;
}
//打印数据
public void show(){
if(isEmpty()){
System.out.println("对列中没有数据");
}
for (int i = 0;i<this.data.length;i++) {
System.out.println("data"+"["+i+"]"+"="+data[i]);
}
}
//取出对头数据
public int peek() throws Exception {
if(isEmpty()){
throw new Exception("队列中没有数据");
}
return this.data[font];
}
}