第九天——栈和队列(基础,用栈实现队列,用队列实现栈)

Tags
栈和队列
 

区别

队列是先进先出,栈是先进后出
notion image
js都是通过数组模拟栈和队列的效果
 

232.用栈实现队列

 
使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。 pop() -- 从队列首部移除元素。 peek() -- 返回队列首部的元素。 empty() -- 返回队列是否为空。

学习链接

个人思路

其实就是维护数组,且只能使用push、pop来模拟队列pushpoppeekempty的操作,这时候需要维护两个栈,输入栈和输出栈,当需要输出时,需要把输入栈的值全导入输出栈中,完成目标

解题代码

var MyQueue = function() { this.inStack = [] this.outStack = [] }; /** * @param {number} x * @return {void} */ MyQueue.prototype.push = function(x) { this.inStack.push(x) }; /** * @return {number} */ MyQueue.prototype.pop = function() { if(!this.outStack.length){ while(this.inStack.length){ this.outStack.push(this.inStack.pop()) } } return this.outStack.pop() }; /** * @return {number} */ MyQueue.prototype.peek = function() { if(!this.outStack.length){ while(this.inStack.length){ this.outStack.push(this.inStack.pop()) } } return this.outStack[this.outStack.length - 1 ] }; /** * @return {boolean} */ MyQueue.prototype.empty = function() { return this.inStack.length === 0 && this.outStack.length === 0 }; /** * Your MyQueue object will be instantiated and called as such: * var obj = new MyQueue() * obj.push(x) * var param_2 = obj.pop() * var param_3 = obj.peek() * var param_4 = obj.empty() */

225. 用队列实现栈

使用队列实现栈的下列操作:
  • push(x) -- 元素 x 入栈
  • pop() -- 移除栈顶元素
  • top() -- 获取栈顶元素
  • empty() -- 返回栈是否为空

学习链接

个人思路

和上一道题类似,可以用双数组的shift、unshift模拟,不一样的是,这里不是维护输入栈和输出栈,而是在pop时存储现在的值
notion image

解题代码

var MyStack = function() { this.queue1 = [] this.queue2 = [] }; /** * @param {number} x * @return {void} */ MyStack.prototype.push = function(x) { this.queue1.push(x) }; /** * @return {number} */ MyStack.prototype.pop = function() { while(this.queue1.length) { this.queue2.push(this.queue1.shift()); } return this.queue2.pop(); }; /** * @return {number} */ MyStack.prototype.top = function() { const x = this.pop() this.push(x) return x }; /** * @return {boolean} */ MyStack.prototype.empty = function() { return this.queue1.length === 0 && this.queue2.length === 0 }; /** * Your MyStack object will be instantiated and called as such: * var obj = new MyStack() * obj.push(x) * var param_2 = obj.pop() * var param_3 = obj.top() * var param_4 = obj.empty() */