zoukankan      html  css  js  c++  java
  • java实现队列

    /**
     * 队列,先进先出
     * 头指针永远指向第一个元素
     * 尾指针永远指向最后一个元素的后一个位置
     * 所有10个容量的数组构成的队列最多容纳9个元素
     *
     * @param <T>
     */
    public class MQueue<T> {
        private final int length = 10;
        private final Object[] entry = new Object[length];
        private int head = 0;
        private int tail = 0;
    
        /**
         * 初始状态头指针和尾指针执行同一个位置
         *
         * @return
         */
        public boolean isEmpty() {
            return head == tail;
        }
    
        /**
         * 队列满,分为两种情况:
         * 1.head在前,tail在后,此时head=0,tail=length-1为满
         * 2.tail在前,head在后,此时head=tail+1为满
         *
         * @return
         */
        public boolean isFull() {
            return head == tail + 1 || (tail == length - 1 && head == 0);
        }
    
        /**
         * 入队列,添加到队尾
         * 如果数组后半部分已满,而数组前半部分有位置,则添加到数组之前半部分
         *
         * @param x
         */
        public void enQueue(T x) {
            if (isFull()) {
                throw new IndexOutOfBoundsException("队列已满");
            }
    
            entry[tail] = x;
            if (tail == length - 1) {
                tail = 0;
            } else {
                tail = tail + 1;
            }
        }
    
        /**
         * 出队列,从队首出
         *
         * @return
         */
        public T deQueue() {
            if (isEmpty()) {
                throw new IndexOutOfBoundsException("队列为空");
            }
            T x = (T) entry[head];
            if (head == length - 1) {
                head = 0;
            } else {
                head = head + 1;
            }
            return x;
        }
    
        public static void main(String[] args) {
            MQueue<Integer> q = new MQueue<>();
            for (int i = 0; i < 9; i++) {
                q.enQueue(i);
            }
            System.out.println(q.head);
            System.out.println(q.tail);
            System.out.println(q.deQueue());
        }
    }
  • 相关阅读:
    Hive metastore三种配置方式
    hive学习(一)hive架构及hive3.1.1三种方式部署安装
    hiveserver2的配置和启动
    spark安装配置
    Sqoop-1.4.6安装部署及详细使用介绍
    搭建本地yum源服务器
    Centos7.X安装impala(RPM方式)
    Hive安装与配置详解
    【图文详解】Hadoop集群搭建(CentOs6.3)
    Linux下实现免密码登录(超详细)
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/15385678.html
Copyright © 2011-2022 走看看