运行起来确实环形了,队列最大值也正常了,但是总觉得有点奇怪
创建的数组长度是要的数组长度+1才行,而且每轮会空一个位置
总体运行正常
测试代码:
import java.util.Scanner; ////////////环形队列测试/////////// public class dome1 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("输入队列最大值"); qu q=new qu(sc.nextInt()+1); boolean bl=true; int a=0; while (bl){ System.out.println("输入1增2删3查"); a=sc.nextInt(); switch (a){ case 1: System.out.println("输入"); a=sc.nextInt(); q.add(a); break; case 2: q.del(); break; case 3: System.out.println(q); break; case 4: bl=false; break; } } } }
环形数组代码:
import java.util.Arrays; public class qu { private int[] arr; private int frist; private int last; private int max; public qu(int max){ this.max=max; frist=0; last=0; arr = new int[max]; } public void add(int a){ if ((last+1)%max==frist){ System.out.println("队列已达上限"); }else { last=(last+1)%max; arr[last]=a; } } public void del(){ if ((frist)==last){ System.out.println("队列空"); return; } frist=(frist+1)%max; arr[(frist)]=0; } @Override public String toString() { return "qu{" + "arr=" + Arrays.toString(arr) + ", frist=" + frist + ", last=" + last + ", max=" + max + '}'; } }