|
|
本文实例为大家分享了javascript实现双端队列的具体代码,供大家参考,具体内容如下4 j1 s4 [; n* m" W) T
1.双端队列) k" q+ N. B5 v# Y0 r" q
0 C2 _; h% F5 _5 p. A
# n6 y/ v4 d! S% G; d; a/ |双端队列是一种允许我们同时从前端和后端添加和移除元素的特殊队列
0 [, [. R$ `' b7 w w! R2.双端队列的应用
3 K8 I! k, u# r9 r3 d9 W' P
5 }* `8 E# u: ?. N
" a# p# h, {' i2 M/ L1 l一个刚买了票的入如果只是还需要再问一些简单的信息,就可以直接回到队伍头部,另外队伍末尾的人如果赶时间也可以直接离开队伍. ~$ k+ V+ U6 G2 b8 X& T. `
3.双端队列的方法
$ I* B* L8 b% ^9 G8 o/ c) z
+ V- D5 {3 l7 P) ]: y5 a2 Y* V) R
0 U. V% G: b8 I- ?- M, C& r; r s1 [addFront(element):该方法在双端队列前端添加新的元素4 D$ z* T! X+ n, n
addBack(element):该方法在双端队列后端添加新的元素(实现方法和 Queue 类中的enqueue 方法相同)。
3 E3 d/ M, ~# a5 F6 WremoveFront():该方法会从双端队列前端移除第一个元素6 r* Q& s& i# m! H
removeBack():该方法会从双端队列的后端移除第一个元素. ]* w! I- ?, b8 R. V+ @
peekFront():该方法返回双端队列的第一个元素。
- j# R) V) q! [6 OpeekBack()):该方法返回双端队列后端的第一个元素。+ N1 H' y) m! L' ~6 l
4.实现! H) x0 n! D, b K6 n0 O
$ X) P- M, x+ p) {
[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 |
|