队列和双端队列
队列数据是遵循先进先出(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 } }
以自己现在的努力程度,还没有资格和别人拼天赋