(365)
(8)
(130)
(155)
(50)
(22)
分类: java
2021-07-12 17:21:41
import java.awt.font;
import java.util.scanner;
import javax.management.runtimeerrorexception;
public class circlearrayqueuedemo {
public static void main(string[] args) {
//创建队列
circlearrayqueue circlearrayqueue = new circlearrayqueue(4);
char key = ' ';
scanner scanner = new scanner(system.in);
boolean loop = true;
while(loop) {
system.out.println("s(show):显示队列");
system.out.println("e(exit):退出程序");
system.out.println("a(add):添加数据到队列");
system.out.println("g(get):从队列取出数据");
system.out.println("h(head):查看队列头的数据");
key = scanner.next().charat(0);
switch (key) {
case 's':
circlearrayqueue.showqueue();
break;
case 'e':
circlearrayqueue.showqueue();
break;
case 'a':
system.out.println("输入一个数");
int value = scanner.nextint();
circlearrayqueue.addqueue(value);
break;
case 'g':
try {
int res = circlearrayqueue.getqueue();
system.out.printf("取出的数据是%d\n",res);
}catch (exception e) {
system.out.println(e.getmessage());
}
break;
case 'h':
try {
int res = circlearrayqueue.headqueue();
system.out.printf("队列头的数据是%d\n",res);
}catch (exception e) {
system.out.println(e.getmessage());
}
break;
default:
scanner.close();
loop = false;
break;
}
}
system.out.println("程序退出");
}
}
//队列
class circlearrayqueue{
private int maxsize;
private int front;
private int rear;
private int[] arr;
//构造器
public circlearrayqueue(int arrmaxsize) {
maxsize = arrmaxsize;
front = 0;
rear = 0;
arr = new int[maxsize];
}
//判满
public boolean isfull() {
return (rear 1)%maxsize == front;
}
//判空
public boolean isempty() {
return rear == front;
}
//入队
public void addqueue(int n) {
if(isfull()) {
system.out.println("队列已满,不能再添加!");
return;
}
//添加数据
arr[rear] = n;
//rear后移
rear = (rear 1) % maxsize;
}
//出队
public int getqueue() {
if(isempty()) {
throw new runtimeexception("队列为空,不可取出元素!");
}
//取值
int value = arr[front];
//front后移
front = (front 1)%maxsize;
return value;
}
//遍历
public void showqueue() {
if(isempty()) {
system.out.println("队列为空!");
return;
}
for(int i = front; i < front size(); i ) {
system.out.printf("arr[%d]=%d\n",i % maxsize, arr[i % maxsize]);
}
}
//求队列有效数据的个数
public int size() {
return (rear maxsize - front) % maxsize;
}
//显示队头元素
public int headqueue() {
if(isempty()) {
throw new runtimeexception("队列为空,不可取出元素!");
}
return arr[front];
}
}
上一篇:
下一篇: