練習-循環キュー1


1.現在のキューから値を取るにつれて、最終的にはキューが同時に空と判断する、満と判断する場合がある.現在のキューは再利用できません.
public class ArrayQueueDemo {
     

    public static void main(String[] args) {
     
        ArrayQueue arrayQueue = new ArrayQueue(3);
        char key = ' ';
        boolean loop = true;
        Scanner scanner = 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):    ");
            key = scanner.next().charAt(0);
            switch (key) {
     
                case 's':
                    arrayQueue.showQueue();
                    break;
                case 'a':
                    System.out.println("     ");
                    int value = scanner.nextInt();
                    arrayQueue.addQueue(value);
                    break;

                case 'g':
                    try {
     
                        int res = arrayQueue.getQueue();
                        System.out.printf("      %d
"
, res); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 'h': try { int res = arrayQueue.headQueue(); System.out.printf(" %d
"
, res); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 'e': loop = false; break; default: break; } } System.out.println(" "); } } class ArrayQueue { private int maxSize; private int front; private int rear; private int[] arr; public ArrayQueue(int arrMaxSize) { maxSize = arrMaxSize; arr = new int[maxSize]; front = -1;// 。 front rear = -1;// , ( ) } public boolean isFull() { return rear == maxSize - 1; } public boolean isEmpty() { return rear == front; } public void addQueue(int n) { if (isFull()) { System.out.println(" , "); return; } rear++; arr[rear] = n; } public int getQueue() { if (isEmpty()) { throw new RuntimeException(" , "); } front++; return arr[front]; } public void showQueue() { if (isEmpty()) { System.out.println(" , "); return; } for (int i = 0; i < arr.length; i++) { System.out.printf("arr[%d]=%d
"
, i, arr[i]); } } public int headQueue() { if (isEmpty()) { throw new RuntimeException(" , "); } return arr[front + 1]; } }