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

    JS实现队列:

    队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头

    链式队列的实现

    function LinkedQueue() {
        let Node = function (ele) {
            this.ele = ele;
            this.next = null;
        }
    
        let length = 0,
            front, //队首指针
            rear; //队尾指针
        this.push = function (ele) {
            let node = new Node(ele),
                temp;
    
            if (length == 0) {
                front = node;
            } else {
                temp = rear;
                temp.next = node;
            }
            rear = node;
            length++;
            return true;
        }
    
        this.pop = function () {
            let temp = front;
            front = front.next
            length--;
            temp.next = null
            return temp;
        }
    
        this.size = function () {
            return length;
        }
        this.getFront = function () {
            return front;
            // 有没有什么思路只获取队列的头结点,而不是获取整个队列
        }
        this.getRear = function () {
            return rear;
        }
        this.toString = function () {
            let string = '',
                temp = front;
            while (temp) {
                string += temp.ele + ' ';
                temp = temp.next;
            }
            return string;
        }
        this.clear = function () {
            front = null;
            rear = null;
            length = 0;
            return true;
        }
    }
    
    let myQueue = new LinkedQueue();
    
    myQueue.push(1)
    myQueue.push(2)
    myQueue.push(3)
    myQueue.push(4)
    console.log(myQueue.toString()) // 1 2 3 4 
    console.log(myQueue.pop()) // Node { ele: 1, next: null }
    console.log(myQueue.toString()) // 2 3 4

    顺序存储队列:利用js内置Array对象

    function ArrayQueue(){  
        var arr = [];  
            //入队操作  
        this.push = function(element){  
            arr.push(element);  
            return true;  
        }  
            //出队操作  
        this.pop = function(){  
            return arr.shift();  
        }  
            //获取队首  
        this.getFront = function(){  
            return arr[0];  
        }  
            //获取队尾  
        this.getRear = function(){  
            return arr[arr.length - 1]  
        }  
            //清空队列  
        this.clear = function(){  
            arr = [];  
        }  
            //获取队长  
        this.size = function(){  
            return length;  
        }  
    }  
  • 相关阅读:
    Prometheus监控MySQL服务(六)
    Prometheus监控Docker服务(五)
    Grafana与Prometheus集成(四)
    Prometheus监控Linux服务器(三)
    Prometheus配置文件(二)
    elasticdump数据迁移方法
    Prometheus介绍及二进制部署(一)
    PHP二维数组的引用赋值容易犯的错误
    Maven仓库国内镜像站
    加密文件之Java改进版
  • 原文地址:https://www.cnblogs.com/xbblogs/p/9891288.html
Copyright © 2011-2022 走看看