1、基本介绍
2、应用实例(数组模拟队列)
package queue;
import java.util.Scanner;
public class ArrayQueue {
public static void main(String[] args) {
Queue queue = new Queue(3);
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while(loop) {
System.out.println("\n添加数据到队列(i)");
System.out.println("删除队列的数据(r)");
System.out.println("打印队列的数据(p)");
System.out.println("查看队列首元素(g)");
System.out.println("查看队列元素个数(c)");
System.out.println("查看队列是否空(e)");
System.out.println("查看队列是否满(f)");
System.out.println("退出程序(q)~");
System.out.print("请选择你要执行的操作:");
char op = scanner.next().charAt(0);
switch (op) {
case 'i':
System.out.print("请输入要入队的元素:");
int val = scanner.nextInt();
queue.insert(val);
break;
case 'r':
queue.remove();
break;
case 'p':
queue.print();
break;
case 'g':
queue.getFirst();
break;
case 'c':
queue.getCount();
break;
case 'e':
queue.isEmpty();
break;
case 'f':
queue.isFull();
break;
default:
scanner.close();
loop = false;
break;
}
}
}
}
// 数组模拟队列
class Queue {
private int front; // 指向第一个元素
private int rear; // 指向最后一个元素的下一个位置
private int maxSize;
private int[] arr;
public Queue(int maxSize) {
this.front = 0;
this.rear = 0;
this.maxSize = maxSize;
this.arr = new int[maxSize];
}
public void insert(int val) {
if (isFull()) {
throw new RuntimeException("队列满啦!");
}
arr[rear++] = val;
System.out.println("元素入队成功~");
System.out.printf("入队元素:%d\n", val);
}
public void remove() {
if (isEmpty()) {
throw new RuntimeException("队列空荡荡~!");
}
System.out.println("元素出队成功~");
System.out.printf("出队元素:%d\n", arr[front++]);
}
public void print() {
System.out.print("队列元素:");
for (int i = front; i < rear; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public void getFirst() {
if (isEmpty()) {
System.out.println("队列为空,请稍后重试!");
}
System.out.println("队首元素:" + arr[front]);
}
public void getCount() {
int count = rear;
System.out.printf("队列元素个数:%d\n", count);
}
public boolean isEmpty() {
if (front == rear) {
System.out.println("队列为空~");
return true;
}
System.out.println("队列有东西~");
return false;
}
public boolean isFull() {
if (rear == maxSize) {
System.out.println("队列已满~");
return true;
}
System.out.println("还能再装一点~");
return false;
}
}