- 学习数据结构与算法,看完视频,做的笔记
使用数组模拟队列只能使用一次,队列添加达到最大后,全部取出数据就无法再添加了,所以需要使用环形数组队列
public class TestIndex {
public static void main(String[] args) {
System.out.println("系统初始化中");
Sequence sequence = new Sequence(4);
boolean flag = true;
Scanner scanner = null;
while (flag){
scanner = new Scanner(System.in);
System.out.println("【a】添加数据");
System.out.println("【g】取出数据");
System.out.println("【p】打印数据");
System.out.println("【h】查看第一个数据");
System.out.println("【e】系统退出");
String i = scanner.next();
try {
switch (i){
case "a":
System.out.println("请输入一个数");
int anInt = scanner.nextInt();
sequence.add(anInt);
break;
case "g":
System.out.println(sequence.get());
break;
case "p":
sequence.print();
break;
case "h":
System.out.println(sequence.head());
break;
case "e":
scanner.close();
System.out.println("系统退出");
flag=false;
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
class Sequence{
private int front;
private int last;
private int [] arr;
private int maxSize;
public Sequence(int maxSize){
this.maxSize = maxSize;
this.arr = new int[maxSize];
this.front = -1;
this.last = -1;
}
public boolean isEmpty(){
if (front == last){
return true;
}else {
return false;
}
}
public boolean isFull(){
if (front ==maxSize-1){
return true;
}else {
return false;
}
}
public void add(int num){
if (isFull()){
throw new RuntimeException("数组已满");
}else {
this.front++;
this.arr[front] = num;
}
}
public int get(){
if (isEmpty()){
throw new RuntimeException("数组为空,无法取数");
}
return arr[++last];
}
public int head(){
if (isEmpty()){
throw new RuntimeException("数组为空");
}
return arr[last+1];
}
public void print(){
if (isEmpty()){
throw new RuntimeException("数组为空");
}
System.out.println(Arrays.toString(arr));
}
}