java使用数组实现循环队列

class CircleArrayQueue {
     private int size;//队列的长度
     private int[] queue; //队列
     private int head; //后指针
     private int tail; //前指针
     private static final int DEFALUT_SIZE = 10;
    
     public CircleArrayQueue() {
         this.size = DEFALUT_SIZE;
     }
    
     public CircleArrayQueue(int queueSize) {
         if (queueSize <= 0 ) {
             size = DEFALUT_SIZE;
             queue = new int[DEFALUT_SIZE];
         } else {
             size = queueSize;
             queue = new int[queueSize];
         }
     }
    
     public boolean isFull() {
         return (tail + 1) % size == head;
     }
    
     public boolean isEmpty() {
         return tail == head;
     }
    
     public int count() {
         return (tail + size - head) % size;
     }
    
     public void add(int num) {
         if (isFull()) {
             System.out.println("队列已满,不能再添加元素!!");
             return;
         }
         queue[tail] = num;
         tail = (tail + 1) % size;
     }
    
     public int get() {
         if (isEmpty()) {
             throw new RuntimeException("队列为空~~~");
         }
         int num = queue[head];
         head = (head + 1) % size;
         return num;
     }
    
     public int peek() {
         if (isEmpty()) {
             throw new RuntimeException("队列为空~~~");
         }
         return queue[head];
     }
    
     public void list() {
         for (int i = head; i < head + count(); i++) {
             System.out.printf("queue[%d] = %d,", i % size, queue[i % size]);
         }
         System.out.println();
     }
}

posted @ 2020-04-30 15:15  dirsoen  阅读(422)  评论(0)    收藏  举报