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());
        }
    }
  • 相关阅读:
    loj1201(最大独立集)
    hdu4185+poj3020(最大匹配+最小边覆盖)
    【Leetcode】3Sum Closest
    【Leetcode】3Sum
    【Leetcode】Two Sum
    【Leetcode】Longest Consecutive Sequence
    【Leetcode】Median of Two Sorted Arrays
    【Leetcode】Search in Rotated Sorted Array II
    【Leetcode】Search in Rotated Sorted Array
    【Leetcode】Remove Duplicates from Sorted Array II
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/15385678.html
Copyright © 2011-2022 走看看