队列具有先进先出的特点,栈具有先进后出的特点,栈和队列互转是经常遇到的情况
参考LeetCode原题:
225. 用队列实现栈
232. 用栈实现队列
用队列实现栈
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class MyStack { constructor() { this.queue1 = []; this.queue2 = []; } push(val) { this.queue2.push(val); while (this.queue1.length) { this.queue2.push(this.queue1.shift()) } while (this.queue2.length) { this.queue1.push(this.queue2.shift()); } } pop() { if (this.queue1.length) { return this.queue1.shift(); } } top() { if (this.queue1.length) { return this.queue1[0]; } } empty() { return !this.queue1.length } }
|
用栈实现队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| class MyQueue { constructor() { this.stack1 = []; this.stack2 = []; } push(val) { this.stack1.push(val); } pop() { if (!this.stack2.length) { while (this.stack1.length) { this.stack2.push(this.stack1.pop()); }; }; return this.stack2.pop(); } peek() { if (!this.stack2.length) { while (this.stack1.length) { this.stack2.push(this.stack1.pop()); }; }; return this.stack2[this.stack2.length -1]; } empty() { return !this.stack1.length && !this.stack2.length; } }
|