|
|
本文实例为大家分享了javascript实现双端队列的具体代码,供大家参考,具体内容如下% h6 b2 O. ~ _) a
1.双端队列
6 P$ M- ^! [+ i
" t% B+ R& X4 V6 Q
, g) p1 l+ {3 P3 J3 S$ L9 \2 [双端队列是一种允许我们同时从前端和后端添加和移除元素的特殊队列
4 j+ ~: ^& C! |' K' B' \8 a) t2.双端队列的应用
+ R3 e+ [; U2 k6 n4 F* Q
3 F) x) p v2 V6 i9 O7 {
8 k* I5 V" _' k& e一个刚买了票的入如果只是还需要再问一些简单的信息,就可以直接回到队伍头部,另外队伍末尾的人如果赶时间也可以直接离开队伍
' |9 X" c: G4 f5 H6 Y+ V# }3.双端队列的方法
8 H4 d5 v$ p9 W+ Z0 y- ]$ ?2 k- V' f3 L0 D f
* A, p3 \ x6 b/ v/ f8 P3 k& BaddFront(element):该方法在双端队列前端添加新的元素7 U9 Y2 i: |" _7 s# ?$ p: K2 e! H
addBack(element):该方法在双端队列后端添加新的元素(实现方法和 Queue 类中的enqueue 方法相同)。% L5 c, x& i5 K
removeFront():该方法会从双端队列前端移除第一个元素
" _- C0 t1 R8 I5 x8 Y" d* R2 }# U( _removeBack():该方法会从双端队列的后端移除第一个元素* H; R0 k0 O4 p5 ]$ e' j9 z+ w* J+ G
peekFront():该方法返回双端队列的第一个元素。1 h+ o$ H7 B7 }4 H% q
peekBack()):该方法返回双端队列后端的第一个元素。3 E% p4 p" N: Z$ A3 _3 H
4.实现4 M5 ^# Q# A" S6 M% ?1 `
; y- m q- {! u3 W( N
[code]class Deque{ constructor(){ this.items = {}; this.count = 0; this.lowestCount = 0; } // 在双端队列前端添加新元素 addFront(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 = this.items[i-1]; } this.lowestCount = 0; this.items[this.lowestCount] = element; this.count++; } }; addBack(element){ this.count++; this.items[this.count-1] = element; }; removeFront(){ if(this.isEmpty()){ return undefined; } const result = this.items[this.lowestCount]; delete this.items[this.lowestCount]; this.lowestCount++; return result; }; removeBack(){ if(this.isEmpty()){ return undefined; } const result = this.items[this.count-1]; delete this.items[this.count-1]; this.count--; return result; }; peekFront(){ if(this.isEmpty()){ return null; } return this.items[this.lowestCount]; }; peekBack(){ if(this.isEmpty()){ return null; } return this.items[this.count-1]; }; isEmpty(){ return this.count - this.lowestCount == 0; } size(){ return this.count - this.lowestCount; } toString(){ if(this.isEmpty()){ return ''; } let objString = `${this.items[this.lowestCount]}`; for(var i=this.lowestCount+1;i |
|