队列
1.队列是一个有序列表,可以用数组或链表来实现
2.遵循先入先出的原则(先存入队列的数据要先取出,后存入的后取出)
数组模拟队列:
import java.util.Scanner;
public class www {
public static void main(String[] args) {
ww w = new ww(3);
Scanner s = new Scanner(System.in);
boolean loop = true;
while (loop) {
System.out.println("1.添加");
System.out.println("2.取出");
System.out.println("3.展示");
System.out.println("4.退出");
switch (s.next()) {
case "1":
try {
System.out.println("输入一个数字");
w.add(s.nextInt());
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
break;
case "2":
try {
System.out.println(w.get());
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
break;
case "3":
w.show();
break;
case "4":
s.close();
loop = false;
break;
}
}
}
}
class ww {
private int i[];// 数组
private int front;// 后端下标
private int rear;// 前端下标
private int max;// 数组大小
public ww(int max) {
this.max = max;
i = new int[max];
}
// 判断是否为空
private boolean isnull() {
return front == rear;
}
// 判断是否为满
private boolean isfull() {
return front - rear == max;
}
// 添加
public void add(int n) {
if (isfull()) {
throw new RuntimeException("队列满,添加失败");
}
System.err.println(front);
i[front++ % max] = n;
}
// 取出数据
public int get() {
if (isnull()) {
throw new RuntimeException("队列空,取出失败");
}
System.out.println(rear);
return i[rear++ % max];
}
// 遍历数组
public void show() {
for (int j = rear; j < front; j++) {
System.out.println("i[" + j % max + "]" + i[j % max]);
}
}
}