java使用數組實現隊列


隊列的特點: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();
     }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM