From 0eb61a58b38ef5d49ff94177ef69c7cfbca5ac4f Mon Sep 17 00:00:00 2001 From: "qingyi.liu" Date: Wed, 26 May 2021 16:52:44 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0225.=20=E7=94=A8=E9=98=9F?= =?UTF-8?q?=E5=88=97=E5=AE=9E=E7=8E=B0=E6=A0=88JavaScript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0225.用队列实现栈.md | 107 ++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index e045229f..055c2e3d 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -357,8 +357,115 @@ class MyStack: Go: +javaScript: +使用数组(push, shift)模拟队列 +```js + +// 使用两个队列实现 +/** + * Initialize your data structure here. + */ +var MyStack = function() { + this.queue1 = []; + this.queue2 = []; +}; + +/** + * Push element x onto stack. + * @param {number} x + * @return {void} + */ +MyStack.prototype.push = function(x) { + this.queue1.push(x); +}; + +/** + * Removes the element on top of the stack and returns that element. + * @return {number} + */ +MyStack.prototype.pop = function() { + // 减少两个队列交换的次数, 只有当queue1为空时,交换两个队列 + if(!this.queue1.length) { + [this.queue1, this.queue2] = [this.queue2, this.queue1]; + } + while(this.queue1.length > 1) { + this.queue2.push(this.queue1.shift()); + } + return this.queue1.shift(); +}; + +/** + * Get the top element. + * @return {number} + */ +MyStack.prototype.top = function() { + const x = this.pop(); + this.queue1.push(x); + return x; +}; + +/** + * Returns whether the stack is empty. + * @return {boolean} + */ +MyStack.prototype.empty = function() { + return !this.queue1.length && !this.queue2.length; +}; + +``` + +```js + +// 使用一个队列实现 +/** + * Initialize your data structure here. + */ +var MyStack = function() { + this.queue = []; +}; + +/** + * Push element x onto stack. + * @param {number} x + * @return {void} + */ +MyStack.prototype.push = function(x) { + this.queue.push(x); +}; + +/** + * Removes the element on top of the stack and returns that element. + * @return {number} + */ +MyStack.prototype.pop = function() { + let size = this.queue.length; + while(size-- > 1) { + this.queue.push(this.queue.shift()); + } + return this.queue.shift(); +}; + +/** + * Get the top element. + * @return {number} + */ +MyStack.prototype.top = function() { + const x = this.pop(); + this.queue.push(x); + return x; +}; + +/** + * Returns whether the stack is empty. + * @return {boolean} + */ +MyStack.prototype.empty = function() { + return !this.queue.length; +}; + +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)