|
|
本文实例为大家分享了javascript实现双端队列的具体代码,供大家参考,具体内容如下
- P7 `$ t6 S0 [1.双端队列
0 H/ q# b5 N6 s. U% C! {" s8 J' K
+ o$ [3 F9 a$ }双端队列是一种允许我们同时从前端和后端添加和移除元素的特殊队列
( |$ b) l/ f& ^2.双端队列的应用
& g4 q* e# i7 M& \/ A+ e. u- u$ S T$ p/ M
1 W4 F1 [: T v+ {( C( l) d* X一个刚买了票的入如果只是还需要再问一些简单的信息,就可以直接回到队伍头部,另外队伍末尾的人如果赶时间也可以直接离开队伍1 g9 u. A, l7 V+ O" T' w
3.双端队列的方法$ T5 ^) X) ^& U* d# @7 }. B8 d: O
j2 T; u; \" [* F+ |# ]+ U* w! p: V
addFront(element):该方法在双端队列前端添加新的元素
8 d2 A. D7 y0 J, n; N# PaddBack(element):该方法在双端队列后端添加新的元素(实现方法和 Queue 类中的enqueue 方法相同)。2 ?- r1 t4 }1 w1 E- _
removeFront():该方法会从双端队列前端移除第一个元素% b! F6 \% D! w6 @8 U. C# }8 X& G5 u
removeBack():该方法会从双端队列的后端移除第一个元素9 `8 M2 O& }" k4 O$ L5 @
peekFront():该方法返回双端队列的第一个元素。
5 q% P4 u# U0 w3 Q+ G5 Q2 opeekBack()):该方法返回双端队列后端的第一个元素。
; q+ @0 w7 j+ a3 J5 E4.实现, ?4 ]0 ~; G( {$ U$ N {8 w( @
9 |( ?) ?6 H* T2 r* t) |$ 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 |
|