• 算法 之 队列的简单创建


    相对于其他的数据结构,队列是十分简单的。这里也不多做讲解,只是用代码来写一个简单的队列,让实现插入和删除等操作:

    package Queue;
    
    
    public class Queue{
        private int maxSize;          //队列的容量存储大小
        private long[] queueArray;    //用数组来存储队列的对象
        private int front;            //队列的头指针
        private int rear;            //队列的尾指针
        private int nElems;            //用于表示队列的长度
        
        public Queue(int s){
            maxSize = s ;
            queueArray = new long[maxSize];
            front = 0;
            rear = -1;
            nElems = 0;
        }
        //向队列中加入数据
        public void insert(long value){
            if (rear == maxSize - 1) {
                rear = -1;
            }
            queueArray[++rear] = value;
            nElems++;
        }
        //从队列中移除数据
        public long remove(){
            long temp = queueArray[front++];
            if (front == maxSize) {
                front = 0;
            }
            nElems--;
            return temp;
        }
        //查看当前的队首元素
        public long peek(){
            return queueArray[front];
        }
        //判断队列是否为空
        public boolean isEmpty() {
            return (nElems == 0);
        }
        //判断队列是否已满
        public boolean isFull(){
            return (nElems == maxSize-1);
        }
        //队列的大小
        public int size(){
            return nElems;
        }
    }

    在代码中测试:

    package Queue;
    
    public class QueueApp {
        public static void main(String[] args){
            Queue queue = new Queue(5);
            queue.insert(10);
            queue.insert(20);
            queue.insert(30);
            queue.insert(40);
            
            queue.remove();
            queue.remove();
            
            queue.insert(22);
            queue.insert(33);
            while(!queue.isEmpty()){
                long n = queue.remove();
                System.out.print(" " + n);
            }
            System.out.println();
        }
    }

     结果:

     30 40 22 33
    

     

  • 相关阅读:
    Spring AOP capabilities and goals
    java Design Patterns
    CDI Features
    connector for python实验
    spring ref &history&design philosophy
    LDAP & Implementation
    RESTful Levels & HATEOAS
    运维管理利器系列--ipmitool
    CentOS8.2同步阿里云Zabbix镜像到本地,本地搭建Zabbix仓库
    CentOS8.2同步阿里云Ceph镜像到本地,本地搭建ceph仓库
  • 原文地址:https://www.cnblogs.com/mercuryli/p/5005687.html
Copyright © 2020-2023  润新知