package com.wmx.queue;
import java.util.Scanner;
/**
* @Description 简单队列
* @Author 吴满心
* @Date 2022/9/12 8:40
* @Version 1.0
*/
public class ArrayQueueDemo {
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(10);
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("1.显示队列\n2.退出程序\n3.添加数据到队列\n4.从队列中取出数据\n5.查看队列头的数据\n6.查看尾部数据");
int key = scanner.nextInt();
switch (key) {
case 1:
arrayQueue.show();
break;
case 2:
System.exit(0);
break;
case 3:
System.out.println("请输入一个数");
int num = scanner.nextInt();
arrayQueue.addQueue(num);
break;
case 4:
System.out.println(arrayQueue.getQueue());
break;
case 5:
arrayQueue.head();
break;
case 6:
arrayQueue.last();
break;
default:
System.out.println("暂时没有该功能");
break;
}
}
}
}
class ArrayQueue {
/**
* 表示数组的最大容量
*/
private int maxSize;
/**
* 队列头
*/
private int front;
/**
* 队列尾
*/
private int rear;
/**
* 该数据用于存放数据
*/
private int[] arr;
public ArrayQueue(int capacity) {
maxSize = capacity;
arr = new int[maxSize];
//指向队列头
front = 0;
//指向队列尾部
rear = 0;
}
/**
* 判断队列是否已经满了
*
* @return
*/
public boolean isFull() {
if (rear == maxSize) {
System.out.println("队列已经满了");
return true;
}
return false;
}
public boolean isEmpty() {
return rear == front;
}
public void addQueue(int n) {
if (isFull()) {
System.out.println("队列已经满了");
return;
}
arr[rear] = n;
rear++;
}
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空,不可取出数据");
}
return arr[front++];
}
public void show() {
if (isEmpty()) {
System.out.println("队列为空");
return;
}
for (int i = front; i < rear; i++) {
System.out.printf("%d\t", arr[i]);
}
System.out.printf("front为:%s,rear为:%s\n", front, rear);
System.out.println("=======================");
}
public void head() {
System.out.println(arr[front]);
}
public void last() {
System.out.println(arr[rear - 1]);
}
}
Java实现简单队列
最新推荐文章于 2023-07-10 15:56:00 发布