美文网首页
队列的实现

队列的实现

作者: wisdom1991 | 来源:发表于2017-10-31 15:08 被阅读0次

    基于顺序表的队列:

    package StackExercise;
    
    public class OrderQueue<T> {
       //默认的最大长度
       public static final int DEFAULT_SIZE = 20;
       //最大长度
       private int maxSize;
       //当前队列
       private Object[] objs;
       //队列头
       private int head;
       //队列尾
       private int tail;
       //队列长度
       private int size;
    
       //初始化
       public OrderQueue() {
           this(DEFAULT_SIZE);
       }
    
       //初始化
       public OrderQueue(int size) {
           head = 0;
           tail = 0;
           maxSize = size;
           objs = new Object[maxSize];
       }
    
       //获取队列长度
       public int getLength() {
           return size;
       }
    
       //出队
       public T deQueue() {
           T ret = null;
           if (size <= 0) {
               throw new RuntimeException("队列为空!");
           } else {
               size--;
               ret = (T) objs[head];
               objs[head] = null;
               head = ++head % maxSize;
           }
           return ret;
    
       }
    
       //入队
       public void enQueue(T t) {
           if (size == maxSize) {
               throw new RuntimeException("队列已满!");
           } else {
               size++;
               objs[tail] = (Object) t;
               tail = ++tail % maxSize;
           }
       }
    
       //打印
       public void print() {
           int start = head;
           while (start != tail) {
               System.out.print(objs[start] + "\n");
               start = ++start % maxSize;
           }
       }
    }
    

    基于链表形式的有空再补充。

    相关文章

      网友评论

          本文标题:队列的实现

          本文链接:https://www.haomeiwen.com/subject/ycybpxtx.html