欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java使用数组实现队列

程序员文章站 2022-05-04 11:07:06
队列的特点:FIFO先进先出class ArrayQueue { private int size;//队列的长度 private int[] queue; //队列 private int front; //后指针 private int rear; //前指针 private static fi... ......

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