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