|
|
本文实例为大家分享了javascript实现双端队列的具体代码,供大家参考,具体内容如下( g+ p' \8 p- U( P! `7 o' D; m& L
1.双端队列
# f$ B- w" z7 j# Q5 v5 x1 T2 x% [8 W: C9 l- \
- o8 d3 e& N, g# V3 @) G双端队列是一种允许我们同时从前端和后端添加和移除元素的特殊队列; J7 ^+ k9 c% y% ]) |$ A3 {5 N
2.双端队列的应用* }" I# F/ n0 `( J
- M; R# ]: ~9 }4 O+ j
) n) u; {6 ^4 P8 f
一个刚买了票的入如果只是还需要再问一些简单的信息,就可以直接回到队伍头部,另外队伍末尾的人如果赶时间也可以直接离开队伍
" c* n3 }# E+ P; L4 B3.双端队列的方法
8 [8 `/ H& I% B/ `: J3 y3 I8 L {3 k1 E0 o0 k
' h" R% v" ?' P, A. U1 N0 o, waddFront(element):该方法在双端队列前端添加新的元素4 B8 N# i% x# F5 I
addBack(element):该方法在双端队列后端添加新的元素(实现方法和 Queue 类中的enqueue 方法相同)。
8 W) ^7 s4 g9 @removeFront():该方法会从双端队列前端移除第一个元素: Z2 p* V: G; J" P1 l
removeBack():该方法会从双端队列的后端移除第一个元素+ v4 l: I* z7 _+ y% o: c, \, \1 e
peekFront():该方法返回双端队列的第一个元素。) v. m. K* `7 \, M$ B, E5 u: C
peekBack()):该方法返回双端队列后端的第一个元素。
1 P! c: ?! H8 s0 D" q4.实现- R* C8 L) D0 j3 y3 R
6 x) }6 b$ L/ Y: a" k. j- q3 ][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 |
|