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

    数组队列

    用数组实现的队列,也叫循环队列。就是定义一个数组,用两个下标head,tail表示队头和队尾。当队头和队尾相等时,队列为空。当队尾+1等于队头时,队列为满。

    注意tail的值,当插入一个元素时tail=1 szie=1,两个时tail=2 size=2,三个时tail=0 size=3,四个时报错“is full”

    package Algorithm;
    
    public class QueueByArray {
        private Object[] queue;
        final static int DEFAULT_MAX_SIZE = 100;
        int length, head, tail;
    
        private void init() {
            queue = new Object[length];
            head = tail = 0;
        }
    
        QueueByArray() {
            length = DEFAULT_MAX_SIZE;
            init();
        }
    
        QueueByArray(int size) {
            length = size;
            init();
        }
    
        public boolean isFull() {
            return size() == length;
    
        }
    
        public boolean isEmpty() {
            return size() == 0;
        }
    
        public int size() {
            if (queue[tail] != null && tail == head) {
                return length;
            }
    
            return (tail - head + length) % length;
        }
    
        public void clear() {
            queue = null;
            queue = new Object[length];
        }
    
        // in queue
        public void put(Object o) throws Exception {
            if (isFull()) {
                System.out.println(head);
                System.out.println(tail);
                throw new Exception("the queue is full!");
            } else {
                queue[tail] = o;
                tail = (tail + 1) % length;
            }
        }
    
        // out queue
        public Object get() throws Exception {
            if (isEmpty()) {
                throw new Exception("the queue is empty!");
            } else {
                final Object o = queue[head];
                queue[head] = null;
                head = (head + 1) % length;
                return o;
            }
        }
    
        public static void main(String[] args) throws Exception {
            final QueueByArray myqueue = new QueueByArray(3);
    
            for (int i = 111; i < 114; i++) {
                myqueue.put(i);
            }
            System.out.println("head==" + myqueue.head + ";tail==" + myqueue.tail + ";size=="
                    + myqueue.size());
    
            while (myqueue.size() > 0) {
                System.out.println(myqueue.get());
            }
    
        }
    
    }


    输出:

    head==0;tail==0;size==3
    111
    112
    113

  • 相关阅读:
    [每日一题]石子合并 -- 区间DP
    [每日一题]: 最长上升子序列 AND 最长不上升子序列
    [每日一题]:最大子矩阵和
    入门DP--最大子段和
    [转载]:正确的提问方式
    springmvc.xml
    service层springservice.xml文件
    aop切面配置
    配置事务通知
    短信验证
  • 原文地址:https://www.cnblogs.com/pu20065226/p/10307622.html
Copyright © 2011-2022 走看看