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;  
        }  
    }  
  • 相关阅读:
    Door Frames CodeForces
    POJ 3090 Visible Lattice Points (ZOJ 2777)
    从斐波那契到矩阵快速幂
    Recursive sequence (矩阵快速幂)2016ACM/ICPC亚洲区沈阳站
    c++ 类实现 AVL树容器(包含迭代器)
    c++ 链表类的实现(包含迭代器)
    HDU
    【几何+模拟】二次元变换 计蒜客
    【bfs+链式向前星】防御僵尸(defend)计蒜客
    deque in Python
  • 原文地址:https://www.cnblogs.com/xbblogs/p/9891288.html
Copyright © 2011-2022 走看看