From 4eb950d5f78d893bd9a649e0ebec44d023f44376 Mon Sep 17 00:00:00 2001 From: "qingyi.liu" Date: Wed, 26 May 2021 16:25:47 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0232.=E7=94=A8=E6=A0=88?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E9=98=9F=E5=88=97JavaScript=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/0232.用栈实现队列.md | 55 +++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index 7c91a0dd..10314a08 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -353,6 +353,61 @@ func (this *MyQueue) Empty() bool { */ ``` + javaScript: + + ```js + // 使用两个数组的栈方法(push, pop) 实现队列 + /** + * Initialize your data structure here. + */ +var MyQueue = function() { + this.stack1 = []; + this.stack2 = []; +}; + +/** + * Push element x to the back of queue. + * @param {number} x + * @return {void} + */ +MyQueue.prototype.push = function(x) { + this.stack1.push(x); +}; + +/** + * Removes the element from in front of queue and returns that element. + * @return {number} + */ +MyQueue.prototype.pop = function() { + const size = this.stack2.length; + if(size) { + return this.stack2.pop(); + } + while(this.stack1.length) { + this.stack2.push(this.stack1.pop()); + } + return this.stack2.pop(); +}; + +/** + * Get the front element. + * @return {number} + */ +MyQueue.prototype.peek = function() { + const x = this.pop(); + this.stack2.push(x); + return x; +}; + +/** + * Returns whether the queue is empty. + * @return {boolean} + */ +MyQueue.prototype.empty = function() { + return !this.stack1.length && !this.stack2.length +}; + ``` +