首页 > 其他 > 详细

队列和双端队列

时间:2020-07-01 22:51:49      阅读:55      评论:0      收藏:0      [点我收藏+]

队列数据是遵循先进先出(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
    }
}

    

队列和双端队列

原文:https://www.cnblogs.com/zhenjianyu/p/13221760.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!