标签:import 位置 方法 OLE ack oid char int() 变量
思路如下:
队列中有效的数据的个数(rear + maxSize - front)% maxSize
//考虑到是环形数组,i应该取模
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;
}
package Array;
import java.util.Scanner;
public class CircleArrayQueue {
public static void main(String[] args) {
CircleQueue arrayQue=new CircleQueue(4);//设置4, 其队列的有效数据最大是3
Scanner scanner = new Scanner(System.in);
boolean loop=true;
char key=‘ ‘;
while (loop){
System.out.print("s:显示队列");
System.out.print("a:添加数据到队列");
System.out.print("g:取出队列数据");
System.out.print("h:查看数据头");
System.out.print("e:退出程序");
key = scanner.next().charAt(0);
switch (key){
case ‘s‘:
arrayQue.showQueue();
break;
case ‘a‘:
System.out.println("请输入数据");
try {
arrayQue.addQueue(scanner.nextInt());
}catch (Exception e){
e.getMessage();
}
break;
case ‘g‘:
try{
int res = arrayQue.getQueue();
System.out.println("取出来的数据是"+res);
}catch (Exception e){
e.getMessage();
}
break;
case ‘h‘:
try{
arrayQue.showHead();
}catch (Exception e){
e.getMessage();
}
break;
case ‘e‘:
scanner.close();
loop=false;
break;
default:
break;
}
}
}
}
class CircleQueue{
private int MaxSize;
private int front;
private int rear;
private int[]arr;
public CircleQueue(int maxSize){
MaxSize=maxSize;
arr=new int[MaxSize];
front=0;
rear=0;
}
//判断队列是否满
public boolean isFull(){
return (rear+1)%MaxSize==front;
}
//判断队列是否为空
public boolean isEmpty(){
return front==rear;
}
//添加数据
public void addQueue(int n){
if (isFull()){
System.out.println("队列已满");
}
arr[rear]=n;
rear=(rear+1)%MaxSize;
}
//取出数据
public int getQueue(){
if (isEmpty()){
throw new RuntimeException("队列已空");
}
//这里需要分析出front是指向队列的第一个元素
// 1.先把front 对应的值保留到一个临时变量
// 2.将front后移,考虑取模
//3.将临时保存的变量返回
int value=arr[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 showHead(){
if (isEmpty()){
throw new RuntimeException("队列已空");
}
return arr[front];
}
}
标签:import 位置 方法 OLE ack oid char int() 变量
原文地址:https://www.cnblogs.com/chaostudy/p/12942037.html