共计 1270 个字符,预计需要花费 4 分钟才能阅读完成。
双端队列是与队列相似的项的有序汇合,其实实质就是队列,只不过是前端与后端都反对插入和删除操作的队列,更实用,所以也就不存在先进先出这种说法了。
咱们能够通过数组来实现,然而为了写出一个更高效得数据结构,应用对象来实现。
class Deque{constructor(){
this.count= 0;
this.lowestCount = 0;
this.items = {};}
isEmptry(){return this.size() === 0;
}
size(){return this.count - this.lowestCount;}
clear(){
this.count= 0;
this.lowestCount = 0;
this.items = {};}
toString(){if(this.isEmptry()){return '';}
let objString = `${this.items[this.lowestCount]}`;
for (let i=this.lowestCount+1;i<this.count;i++) {objString = `${objString},${this.items[i]}`;
}
return objString;
}
addBack(el){this.item[this.count]=el;
this.count++;
}
addFront(el){if(this.isEmptry()){this.addBack(el);
}else if(this.lowestCount>0){
this.lowestCount--;
this.item[this.lowestCount]=el;
}else{for(let i=this.count;i>0;i--){this.item[i]=this.item[i-1];
}
this.count++;
this.lowestCount=0;
this.item[0]=el;
}
}
removeFront(){if(this.isEmptry()){return undefined;}
let c = this.items[this.lowestCount];
delete this.items[this.lowestCount];
this.lowestCount++;
return c;
}
removeBack(){if (this.isEmpty()) {return undefined;}
this.count--;
let c = this.items[this.count];
delete this.items[this.count];
return c;
}
peekFront() {if (this.isEmpty()) {return undefined;}
return this.items[this.lowestCount];
}
peekBack() {if (this.isEmpty()) {return undefined;}
return this.items[this.count - 1];
}
}
该内容借鉴于学习 javascript 数据结构与算法。
正文完
发表至: javascript
2020-09-08