|
|
本文实例为大家分享了javascript实现双端队列的具体代码,供大家参考,具体内容如下 \# r8 k. j1 z
1.双端队列
* u5 ?( e! C6 j9 M6 t
( V( F8 Q) u4 o) h0 Q. E4 t' B" ?8 n/ d2 G; n
双端队列是一种允许我们同时从前端和后端添加和移除元素的特殊队列
" X2 ] X3 C$ w6 W" O- ^2.双端队列的应用
. G6 { [6 b2 j0 | S% P' @. r5 \- r4 \$ g' y' p K2 y
1 s: l9 x3 n# B) k$ \: n( G一个刚买了票的入如果只是还需要再问一些简单的信息,就可以直接回到队伍头部,另外队伍末尾的人如果赶时间也可以直接离开队伍* ^; B2 h0 @1 t4 R' h) q+ ^
3.双端队列的方法/ _# ?/ t! t, r j1 G4 m' d- g
1 L. ]5 L' a o$ y, n
# X$ y! X: B5 M$ l
addFront(element):该方法在双端队列前端添加新的元素! V1 v8 U9 i9 U1 a& t
addBack(element):该方法在双端队列后端添加新的元素(实现方法和 Queue 类中的enqueue 方法相同)。
0 [# |5 i1 S8 p# nremoveFront():该方法会从双端队列前端移除第一个元素1 g; D0 J# E3 j# q
removeBack():该方法会从双端队列的后端移除第一个元素
& X; ?- G$ R8 Y) a" UpeekFront():该方法返回双端队列的第一个元素。6 k* S4 S6 U% H) I: e
peekBack()):该方法返回双端队列后端的第一个元素。
2 V" r" V7 R# m' {( _- |* [4.实现* S9 a- m/ E, t0 v9 W4 M
2 N W; O1 S [5 r1 u; E: \
[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 |
|