java使用数组实现队列

旧时模样 提交于 2020-05-01 18:19:28

队列的特点:FIFO先进先出

class ArrayQueue {
     private int size;//队列的长度
     private int[] queue; //队列
     private int front; //后指针
     private int rear; //前指针
     private static final int DEFALUT_SIZE = 10;
    
     public ArrayQueue() {
         this.size = DEFALUT_SIZE;
     }
    
     public ArrayQueue(int queueSize) {
         if (queueSize <= 0 ) {
             size = DEFALUT_SIZE;
             queue = new int[DEFALUT_SIZE];
         } else {
             size = queueSize;
             queue = new int[queueSize];
         }
         front = -1;
         rear = -1;
     }
    
     public boolean isFull() {
         return rear == size - 1;
     }
    
     public boolean isEmpty() {
         return rear == front;
     }
    
     public void add(int n) {
         if (isFull()) {
             System.out.println("队列已满,不能再添加数据");
             return;
         }
         queue[++rear] = n;
     }
    
     public int get() {
         if (isEmpty()) {
             throw new RuntimeException("队列已空,没有数据了");
         }
         return queue[++front];
     }
    
     public int peek() {
         if (isEmpty()) {
             throw new RuntimeException("队列已空,没有头元素了");
         }
         return queue[front + 1];
     }
    
     public void list() {
         for (int i : queue) {
             System.out.printf("%d\t", i);
         }
         System.out.println();
     }
}


























































标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!