一,数组模拟队列
1.定义
队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。
2.举例个例子
去银行排对取钱
3.问题代码样例
public class ArrayQueueDemo {
public static void main(String[] args) {
ArrayQueue queue = new ArrayQueue(3);
char key = ' ';
boolean loop = true;
Scanner sc = new Scanner(System.in);
while (loop) {
System.out.println("s(show)显示队列");
System.out.println("a(add)添加队列");
System.out.println("g(get)获取队列");
System.out.println("h(head)显头队列");
System.out.println("e(exist)终止队列");
key = sc.next().charAt(0);//接收一个字符
switch (key) {
case 's':
queue.showQueue();
break;
case 'g':
try {
int v = queue.getQueue();
System.out.printf("取出数据为:%d\n", v);
}catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'a':
System.out.println("请输入一个数字");
int value = sc.nextInt();
queue.addQueue(value);
break;
case 'h':
int h = queue.headQueue();
System.out.printf("头数据为:%d\n", h);
break;
case 'e':
loop = false;
break;
}
}
}
}
class ArrayQueue {
private int maxSize; //队列最大长度
private int front; //队列头
private int rear; //队列尾
private int[] arr; //数组
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
this.front = -1;
this.rear = -1;
this.arr = new int[maxSize];
}
//查看方法
public void showQueue() {
if (rear == front) {
System.out.println("队列为空");
return;
}
for (int i = 0; i < arr.length; i++) {
System.out.printf("arr[%d] = %d\n", i, arr[i]);
}
}
//添加方法
public boolean addQueue(int ele) {
if (rear + 1 == maxSize) {
System.out.println("对了已满");
return false;
}
rear++;
arr[rear] = ele;
return true;
}
//获取方法
public int getQueue() {
if (rear == front) {
throw new RuntimeException("队列为空");
}
return arr[++front];
}
//显示头队列
public int headQueue() {
isNull();
return arr[front + 1];
}
public void isNull() {
if (rear == front) {
throw new RuntimeException("队列为空");
}
}
}
s(show)显示队列
a(add)添加队列
g(get)获取队列
h(head)显头队列
e(exist)终止队列
a
请输入一个数字
1
s(show)显示队列
a(add)添加队列
g(get)获取队列
h(head)显头队列
e(exist)终止队列
h
头数据为:1
s(show)显示队列
a(add)添加队列
g(get)获取队列
h(head)显头队列
e(exist)终止队列
s
arr[0] = 1
arr[1] = 0
arr[2] = 0
s(show)显示队列
a(add)添加队列
g(get)获取队列
h(head)显头队列
e(exist)终止队列
e