自己悟的
可能有错误
package com.datastructure;
import java.util.*;
/**
* 环形队列
*/
public class Queue {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Aaa aaa = new Aaa(10);
while (true) {
System.out.print("输入你要做什么\t");
System.out.print("add:添加数据\t");
System.out.print("show:查看全部\t");
System.out.print("get:取出数据\t");
System.out.print("head:查看头部\t");
System.out.println("exit:退出");
switch (sc.next()) {
case "show":
aaa.showData();
break;
case "add":
System.out.println("请输入要添加的数字");
aaa.add(sc.nextInt());
break;
case "get":
try {
System.out.println(aaa.getData());
} catch (Exception e) {
System.out.println("数据已经取完了");
e.printStackTrace();
}
break;
case "head":
try {
System.out.println(aaa.getHead());
} catch (Exception e) {
System.out.println("没有数据");
e.printStackTrace();
}
break;
case "exit":
return;
default:
break;
}
}
}
}
class Aaa {
private static int maxSize; //最大长度
private static int head; //头
private static int tail; //尾
private static int[] queue; //数组
private static int length;
public Aaa(int maxSize) {
Aaa.maxSize = maxSize;
queue = new int[maxSize];
head = 0;
tail = 0;
length = 0;
}
/**
* 判断队列是否为空
* @return
*/
public boolean isEmpty() {
if (length == 0) {
return true;
}
return false;
}
/**
* 判断队列是否已满
* @return
*/
public boolean isFull() {
return length == maxSize;
}
public void add(int data) {
if (isFull()) {
System.out.println("数组已满");
return;
}
//判断是否到队列尾部,如果到尾部就把指向头部
if (tail+1 > maxSize) {
queue[0] = data;
tail = 1;
length++;
return;
}
queue[tail++] = data;
length++;
}
/**
* 查看队列头部
* @return
*/
public int getHead() {
if (isEmpty()) {
throw new RuntimeException("数组为空");
}
return queue[head];
}
/**
* 取出队列中数据
* @return
*/
public int getData() {
if (isEmpty()) {
throw new RuntimeException("数组为空");
}
//判断是否到队列尾部,如果到尾部就把指向头部
if (head+1 > maxSize) {
length--;
//重置队列头,因为下方已经把下标0取出,所以为1 上方增加同理
head = 1;
return queue[0];
}
length--;
return queue[head++];
}
/**
* 查看队列内数据
*/
public void showData() {
if (isEmpty()) {
System.out.println("没有数据");
return;
}
for (int i = 0; i < length; i++) {
System.out.printf("arr[%d]=%d\n", (head+i)%maxSize, queue[(head+i)%maxSize]);
}
System.out.println("tail="+tail + "\thead=" + head + "\tlength="+length);
}
}