import java.util.Scanner;
public class ArrayQueueDemo1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayQueue1 arrayQueue = new ArrayQueue1(4);
char key = ' ';
boolean flag = true;
while (flag){
System.out.println("s.展示数据");
System.out.println("e.退出程序");
System.out.println("a.添加数据");
System.out.println("g.从队列中获取数据.");
System.out.println("h.查看队列头的数据.");
System.out.println("");
key = scanner.next().charAt(0);
switch (key){
case 's':
arrayQueue.list();
break;
case 'a':
System.out.println("请输入一个数: ");
int data = scanner.nextInt();
arrayQueue.add(data);
break;
case 'g':
try {
int res = arrayQueue.getQueue();
System.out.println("取出的数据是: "+res);
}catch (Exception e){
e.getMessage();
}
break;
case 'h':
try {
int res = arrayQueue.headQueue();
System.out.println("队列头的数据为: "+res);
}catch (Exception e){
e.getMessage();
}
break;
case 'e':
scanner.close();
flag = false;
break;
default:
break;
}
}
}
}
class ArrayQueue1{
private int maxSize;
private int front;
private int rear;
private int [] arr ;
public ArrayQueue1(int maxSize){
this.maxSize = maxSize;
arr = new int[maxSize];
}
public boolean isFull (){
return (rear+ 1) % maxSize == front;
}
public boolean isEmpty(){
return front == rear;
}
public int getSize(){
if (isEmpty()){
System.out.println("队列为空!!!");
return 0;
}
return (rear + maxSize - front) % maxSize;
}
public void add(int data){
if (isFull()){
System.out.println("队列中的数据已经满了,不能再添加数据了");
return;
}
arr[rear] = data;
rear = (rear + 1) % maxSize ;
}
public int getQueue(){
if (isEmpty()){
throw new RuntimeException("队列为空,不能取数据");
}
int value = arr[front];
front = (front + 1) % maxSize;
return value;
}
public int headQueue(){
if (isEmpty()) {
throw new RuntimeException("队里的数据是空的,不能取数据");
}
return arr[front + 1];
}
public void list() {
if (isEmpty()){
System.out.println("队里面的数据是空的!!!");
return;
}
int size = getSize();
for (int i = front; i < front + size; i++) {
System.out.printf("arr[%d] = %d\n",i,arr[i]);
}
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-3087.html