咱們能夠經過數組來實現,可是爲了寫出一個更高效得數據結構,使用對象來實現。javascript
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數據結構與算法。前端