リング配列を使って簡単にキューを実現します.

3621 ワード

主な違いは、frontとrearは0から始まります.以前はfrontは最初の元素の前の位置を指していました.rearは最後の元素を指しています.今はfrontに変えて直接に頭の元素を指します.
rearは最後の要素の次の位置を指し、最後に所定の位置を残し、列の実際の使用サイズはmaxSize-1です.
public class CircleArrayQueue {
    public static void main(String[] args) {
        //    
        CircleQueue circleQueue = new CircleQueue(3);

        char key = ' ';
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        while ((loop)) {
            System.out.println("s:     ");
            System.out.println("e:     ");
            System.out.println("a:     ");
            System.out.println("g:       ");
            System.out.println("h:        ");
            key = scanner.next().charAt(0);//      
            switch (key) {
                case 's':
                    circleQueue.showQueue();
                    break;
                case 'a':
                    int value = scanner.nextInt();
                    circleQueue.addQueue(value);
                    break;
                case 'g':
                    try {
                        int result = circleQueue.getQueue();
                        System.out.printf("      %d
", result); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 'h': try { int peek = circleQueue.peek(); System.out.printf(" %d\t", peek); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 'e': scanner.close(); loop = false; default: break; } } System.out.println(" "); } } class CircleQueue{ private int maxSize; // private int front; // private int rear; // private int[] arr; // public CircleQueue(int maxSize) { this.maxSize = maxSize; arr=new int[maxSize]; // front rear 0 } // public boolean isFull() { return (rear+1+maxSize)%maxSize==front; } // public boolean isEmpty() { return front == rear; } public void addQueue(int number) { boolean full = this.isFull(); if (full) { System.out.println(" , "); return; } arr[rear] = number; // rear rear=(rear+1)%maxSize; } // public int getQueue() { boolean empty = this.isEmpty(); if (empty) { throw new RuntimeException(" ! "); } int number = arr[front]; front=(front+1)%maxSize; // return number; } // public void showQueue() { boolean empty = this.isEmpty(); if (empty) { System.out.println(" "); return; } for (int i = front; i < front+size(); i++) { System.out.printf("arr[%d]=%d
",i%maxSize,arr[i%maxSize]); } } // public int size(){ return (rear-front+maxSize)%maxSize; } // public int peek() { boolean empty = this.isEmpty(); if (empty) { throw new RuntimeException(" , "); } return arr[front + 1]; } }