1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| class Deque{ items = {} head = 0 last = 0 addFront(e){ if(this.head===0){ console.log('无法在队头添加了') return; } for(let i=this.last;i>=this.head;i--){ this.items[i]=this.items[i-1] } this.head-- } addBack(e){ this.items[this.last] = e this.last++ } removeFront(){ if(this.isEmpty()){ return; } let res = this.items[this.head] delete this.items[this.head] this.head++ return res } removeBack(){ if(this.isEmpty()){ return; } let res = this.items[this.last] delete this.items[this.last] this.last-- return res } peekFront(){ return this.items[this.head] } peekBack(){ return this.items[this.last] } isEmpty(){ return this.last === this.head } get size(){ return this.last-this.head } }
|