|
|
本文实例为大家分享了javascript实现双端队列的具体代码,供大家参考,具体内容如下; x" ]$ B, V( N- v* U; `8 ]
1.双端队列
0 } a! d8 \4 }1 L; K
7 i; C7 _+ c$ [- P7 Q S
0 w$ k* G( H+ a2 r0 g) ^双端队列是一种允许我们同时从前端和后端添加和移除元素的特殊队列
* k+ i' z" ^. s, C2.双端队列的应用7 W d( w/ h# K6 y8 l5 l, M. R g
2 y) v) j K8 L4 a9 e: H8 \4 Y
* W; c+ F) ~" h9 A
一个刚买了票的入如果只是还需要再问一些简单的信息,就可以直接回到队伍头部,另外队伍末尾的人如果赶时间也可以直接离开队伍3 _- D3 F, H3 M, z
3.双端队列的方法$ o- e% l8 m' l
3 K9 S9 n4 | E# n7 A! s, J4 q2 o2 G7 d
addFront(element):该方法在双端队列前端添加新的元素( V1 C+ @& C/ e8 F5 A4 ? V- S
addBack(element):该方法在双端队列后端添加新的元素(实现方法和 Queue 类中的enqueue 方法相同)。
& y( v4 @) H' e% IremoveFront():该方法会从双端队列前端移除第一个元素+ O5 @3 d+ r6 X6 D
removeBack():该方法会从双端队列的后端移除第一个元素
* m5 _- K' O a, z1 @" f0 NpeekFront():该方法返回双端队列的第一个元素。( p6 x% z; U d3 G5 G
peekBack()):该方法返回双端队列后端的第一个元素。
" s! ?6 a3 M( {4.实现1 i7 D4 ~9 D; Y
% o" }" o" r0 j7 s7 z) C% f0 t
[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 |
|