|
|
本文实例为大家分享了javascript实现双端队列的具体代码,供大家参考,具体内容如下, ^# W; ?% d; e5 L+ ^0 h+ t
1.双端队列. x/ Y. r" f. y, c. b9 s# z3 p
/ `) [. \' u2 S7 B" u5 l$ e
! c: o O0 g* E) R5 `6 Q双端队列是一种允许我们同时从前端和后端添加和移除元素的特殊队列9 R6 T7 v6 G+ e5 M8 ?/ x
2.双端队列的应用' v& G) K/ C8 `7 w8 T1 Y6 [* S, B0 X
6 z3 D* t$ k4 H0 k! l
" c% X/ H% w6 K" {# q" g
一个刚买了票的入如果只是还需要再问一些简单的信息,就可以直接回到队伍头部,另外队伍末尾的人如果赶时间也可以直接离开队伍. f e6 Y2 z* I: T: ^
3.双端队列的方法
: a' ~0 I z& c% F9 T, q7 q
9 z2 A9 z$ a I+ f6 P
0 V' W2 {6 k) D0 l% JaddFront(element):该方法在双端队列前端添加新的元素
" y3 K/ }: F$ c/ _6 kaddBack(element):该方法在双端队列后端添加新的元素(实现方法和 Queue 类中的enqueue 方法相同)。, \" u. f" x6 q3 n# ^5 h8 d
removeFront():该方法会从双端队列前端移除第一个元素/ Z7 a3 m4 L z7 A9 B
removeBack():该方法会从双端队列的后端移除第一个元素& s. b: p2 c2 ]) _$ p
peekFront():该方法返回双端队列的第一个元素。0 r6 n- l& f& b- v d ?
peekBack()):该方法返回双端队列后端的第一个元素。
+ ]+ U+ U- Q7 d2 q+ V) F4.实现
; j7 e- h$ c1 b5 ^5 B9 v% |2 K* @0 b- p+ `9 H3 P
[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 |
|