|
|
本文实例为大家分享了javascript实现双端队列的具体代码,供大家参考,具体内容如下
) {8 c4 K7 v# t2 M( x1.双端队列# d3 H. N+ V3 Q! A7 h) ~. M' n( Q
, [8 I2 _" G! A0 b. t _! e$ J" o
# ~* S6 g8 M: L1 q# c$ g双端队列是一种允许我们同时从前端和后端添加和移除元素的特殊队列* @& C k8 l% K
2.双端队列的应用
* n+ T. _2 j) l& Q3 x- E. \& @8 F
: Y, `& k$ v7 l- E4 A1 Z$ _. V; H$ B1 G0 j9 L5 A
一个刚买了票的入如果只是还需要再问一些简单的信息,就可以直接回到队伍头部,另外队伍末尾的人如果赶时间也可以直接离开队伍
! a4 }5 d, Q, ~8 Q3.双端队列的方法
, }& F& _5 j+ u- n' n' u; d* f, g; D Z5 w7 W' o0 H3 W4 Y2 ^
) y: W8 A/ Q7 @7 m7 b3 LaddFront(element):该方法在双端队列前端添加新的元素! m( V+ v2 [* @
addBack(element):该方法在双端队列后端添加新的元素(实现方法和 Queue 类中的enqueue 方法相同)。
h `0 i" c2 u( J# o) JremoveFront():该方法会从双端队列前端移除第一个元素
3 A1 L8 H) p) I+ `/ ^6 jremoveBack():该方法会从双端队列的后端移除第一个元素
1 x8 ^8 o* E! \- |$ e/ LpeekFront():该方法返回双端队列的第一个元素。
% L7 x# a* h. i F6 \, mpeekBack()):该方法返回双端队列后端的第一个元素。
3 g) H- F4 h9 W3 v0 L# C4.实现" I- H2 A( _/ F2 ]
; j0 o( X' Y( Z Z( `( {
[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 |
|