zoukankan      html  css  js  c++  java
  • 队列和双端队列

    队列数据是遵循先进先出(FIFO)原则的一组有序的项。队列在尾部添加新元素,并从顶部移除元素。最新添加的元素必须排在队列的末尾。

    class Queue {
        constructor(){
            this.count = 0
            this.lowestCount = 0
            this.items = {}
        }
    }
    Queue.prototype.enqueue = function(element){
        this.items[this.count] = element
        this.count++
    }
    Queue.prototype.dequeue = function(){
        if(this.isEmpty()){
            return undefined
        }
        const result = this.items[this.lowestCount]
        delete this.items[this.lowestCount]
        this.lowestCount++
        return result
    }
    Queue.prototype.peek = function(){
        if(this.isEmpty()){
            return undefined
        }
        return this.items[this.lowestCount]
    }
    Queue.prototype.isEmpty = function(){
        return this.lowestCount == this.count
    }
    Queue.prototype.size = function(){
        return this.count - this.lowestCount
    }
    Queue.prototype.clear = function(){
        this.items = {}
        this.count = 0
        this.lowestCount = 0
    }
    Queue.prototype.toString = function(){
        if(this.isEmpty()){
            return ''
        }
        let str = `${this.items[this.lowestCount]}`
        for(let i = this.lowestCount+1;i < this.count;i++){
            str = `${str},${this.items[i]}`
        }
        return str
    }
    

    双端队列:是一种允许同时从前端和后端添加和移除元素的特殊队列。

    class Deque {
        constructor(){
            this.count = 0
            this.lowestCount = 0
            this.items = {}
        }
    }
    Deque.prototype.addFront = function(element){
        if(this.isEmpty()){
            this.addBack(element)
        }else if(this.lowestCount > 0){
            this.lowestCount--
            this.items[this.lowestCount] = element
        }else{
            for(let i = this.count;i > 0;i--){
                this.items[i] = this.items[i-1]
            }
            this.count++
            this.lowestCount = 0
            this.items[0] = element
        }
    }
    

        

  • 相关阅读:
    HZNU Personal Training 2
    6月30日-助教题解-刺客信条起源
    Educational Codeforces Round 90 (Rated for Div. 2)
    暑假python学习笔记
    HZNU Training 32 for Zhejiang Provincial Competition 2020
    哈夫曼树
    网络流24题
    splay
    生成树计数
    HZNU Training 29 for Zhejiang Provincial Competition 2020
  • 原文地址:https://www.cnblogs.com/zhenjianyu/p/13221760.html
Copyright © 2011-2022 走看看