|
|
本文实例为大家分享了javascript实现双端队列的具体代码,供大家参考,具体内容如下
( H9 V7 E3 b7 M4 S1.双端队列
3 { E* c& G9 F/ \+ \0 D% k# z! ?9 P7 `- E* ~7 c/ L
% i; K. }. H: u6 _, I
双端队列是一种允许我们同时从前端和后端添加和移除元素的特殊队列; S8 W* ^( _; ^: W5 o4 M
2.双端队列的应用
1 s+ A# U, ^- e& e' {7 a7 O2 s, k9 f- q$ y: c
: v' l; ^9 J' }! A6 t
一个刚买了票的入如果只是还需要再问一些简单的信息,就可以直接回到队伍头部,另外队伍末尾的人如果赶时间也可以直接离开队伍( R5 q) c! k6 T- \/ V( p. _" D
3.双端队列的方法
5 L0 d; n& _( B6 o, ?+ L- g' I) z# Y% K, ~( r2 W5 R
! I. _& y& D6 G5 |5 q. F
addFront(element):该方法在双端队列前端添加新的元素
. L( S% A' k2 N) i H; @addBack(element):该方法在双端队列后端添加新的元素(实现方法和 Queue 类中的enqueue 方法相同)。
( b, v E) ^, i& @0 NremoveFront():该方法会从双端队列前端移除第一个元素4 p9 b9 h" {! S8 X6 C
removeBack():该方法会从双端队列的后端移除第一个元素
- n+ T. x4 L( C! y! Q8 YpeekFront():该方法返回双端队列的第一个元素。
: m8 Y; D% Y0 V) `. s, C3 E* upeekBack()):该方法返回双端队列后端的第一个元素。
: j+ G# ?( ~4 o4 `- ^2 \3 k" V4.实现
: n2 C6 X% L6 F" O9 V
: g% j0 G1 S7 T& F3 x' r. f[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 |
|