zoukankan      html  css  js  c++  java
  • 02.数组模拟环形队列

    
    /**
     * 环形队列
     */
    public class ArrayQueueDemo {
        public static void main(String[] args){
            ArrayQueue queue = new ArrayQueue(3);
            queue.add(1);
            queue.show();
            queue.add(2);
            queue.add(3);
            queue.show();
            System.out.println("queue.getHead() = " + queue.getHead());
            queue.remove();
            System.out.println("queue.getHead() = " + queue.getHead());
            queue.show();
            queue.add(4);
            queue.show();
        }
        //arr[0]=1
        //------
        //队列满了
        //arr[0]=1
        //arr[1]=2
        //------
        //queue.getHead() = 1
        //queue.getHead() = 2
        //arr[1]=2
        //------
        //arr[1]=2
        //arr[2]=4
        //------
    }
    class ArrayQueue{
        private int[] arr;
        private int maxSize;//数组的最大容量,可存放元素为maxSize-1
        private int front = 0;//队列头,队列的第一个元素
        private int rear = 0;//队列尾,队列的最后一个元素的下一个位置
    
        public ArrayQueue(int maxSize) {
            this.maxSize = maxSize;
            arr = new int[maxSize];
        }
        //队列是否满了
        public boolean isFull(){
            return (this.rear+1)%maxSize == this.front;
        }
        //队列是否为空
        public boolean isEmpty(){
            return this.rear == this.front;
        }
        public void add(int n){
            if (isFull()){
                System.out.println("队列满了");
                return;
            }
            arr[rear] = n;
            rear = (rear+1) % maxSize;
        }
        public int remove(){
            if (isEmpty()){
                System.out.println("队列为空");
                return -1;
            }
            int i = arr[front];
            front = (front+1) % maxSize;
            return i;
        }
        public void show(){
            // 1 2 3 4 5
            // f     r
            for (int i = front; i < front+size(); i++) {
                System.out.printf("arr[%d]=%d
    ",i % maxSize,arr[i % maxSize]);
            }
            System.out.println("------");
        }
        public int getHead(){
            if (isEmpty()){
                throw new RuntimeException("队列为空");
            }
            return arr[front];
        }
        private int size(){
            return (maxSize - front + rear) % maxSize;
        }
    }
    
  • 相关阅读:
    JAVA --解压缩
    自动事务和手动事务的实验
    Transaction not successfully started&&Could not commit Hibernate transaction;
    POI解决大EXCLE导入崩溃的问题,3MB 7W数据 从入库到查询30s
    使用<c:foreach>同时遍历两个list
    关于Eclipse Tomcat开发中的热部署
    java的单例
    map在JSP页面取值的问题
    JSP问题
    Mybatis控制台打印sql正确,程序执行错误
  • 原文地址:https://www.cnblogs.com/fly-book/p/11630299.html
Copyright © 2011-2022 走看看