|
|
本文实例为大家分享了javascript实现双端队列的具体代码,供大家参考,具体内容如下; q+ h8 S3 T7 E: F* _' Z: T6 O1 P
1.双端队列
* \, K" v" ~9 u. ?5 `
$ M% ^7 p3 Q; Z% Z& [/ ?# P' b/ e8 ~% O) C# x3 U& n0 N
双端队列是一种允许我们同时从前端和后端添加和移除元素的特殊队列
I$ n; O+ a9 d9 m2.双端队列的应用. B+ N k6 W0 b! s% h
! N B. v. k: z" J8 k
6 R- Y6 c1 C7 W+ Q- N2 L一个刚买了票的入如果只是还需要再问一些简单的信息,就可以直接回到队伍头部,另外队伍末尾的人如果赶时间也可以直接离开队伍$ Y3 J( H5 a7 K3 y9 N& X
3.双端队列的方法5 u' q2 K' ~; N: E) e
7 F7 P# B }) L" T T1 L( b1 C% ~8 `8 }9 @7 O
addFront(element):该方法在双端队列前端添加新的元素
( z5 D b7 [/ |: {- t* `# Z$ FaddBack(element):该方法在双端队列后端添加新的元素(实现方法和 Queue 类中的enqueue 方法相同)。/ X& P" S4 \5 B& D* I) h4 {
removeFront():该方法会从双端队列前端移除第一个元素8 K! m4 Y9 R: b- c2 W; |/ R
removeBack():该方法会从双端队列的后端移除第一个元素
! p$ d" O% K+ ]+ [peekFront():该方法返回双端队列的第一个元素。
2 \8 g5 [7 o. A) m! ppeekBack()):该方法返回双端队列后端的第一个元素。
* _) n- C& `/ | x( I4.实现3 n8 u; W, i5 K' S! u" R
- |. ]/ {$ w4 F; u: }! ~# ?[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 |
|