|
|
本文实例为大家分享了javascript实现双端队列的具体代码,供大家参考,具体内容如下2 ]5 T" V! g B9 E: a0 V p
1.双端队列
" h: Y4 H: T3 N2 J7 J- [# G) @3 r9 E! o; c1 M# d5 \
2 |) F% o2 w- c) O# O) Y( H
双端队列是一种允许我们同时从前端和后端添加和移除元素的特殊队列
8 L, N, t: C/ y6 }. ^8 O2.双端队列的应用" e. R. |1 B# \! q* ^' d
$ I3 y( y" _* F3 i+ U- M
' c2 O1 ^3 K- f一个刚买了票的入如果只是还需要再问一些简单的信息,就可以直接回到队伍头部,另外队伍末尾的人如果赶时间也可以直接离开队伍
9 [. A6 Y p* L- d' U" k3.双端队列的方法6 n" D# Y3 z& f$ `: K3 E' ^1 R, e
; H8 d5 c/ P- J. p$ a5 J
( ~5 C ^. v- t; X3 O1 ^5 F
addFront(element):该方法在双端队列前端添加新的元素2 W2 c8 T8 G* ^/ [
addBack(element):该方法在双端队列后端添加新的元素(实现方法和 Queue 类中的enqueue 方法相同)。& L/ b" G$ \# Q$ b& {
removeFront():该方法会从双端队列前端移除第一个元素
5 \5 P3 N, C v3 K* HremoveBack():该方法会从双端队列的后端移除第一个元素
5 n) Q* R% m3 P6 j! j) k5 P+ ]peekFront():该方法返回双端队列的第一个元素。
( ]. t$ J+ f. D' z% O" }peekBack()):该方法返回双端队列后端的第一个元素。
6 s% [! l+ ~. q! g% ?2 X4.实现
& @+ m- S8 U6 O9 d8 | {( E
* Z8 J; K! W/ e q[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 |
|