From 4e53da9e3ef1d044fa801465457fe72a818eb633 Mon Sep 17 00:00:00 2001 From: daluozha <561890199@qq.com> Date: Tue, 27 Apr 2021 18:13:08 +0800 Subject: [PATCH] =?UTF-8?q?leetcode=20225=20=E8=A1=A5=E5=85=85js=E7=89=88?= =?UTF-8?q?=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../栈和队列/225.用队列实现栈.md | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/animation-simulation/栈和队列/225.用队列实现栈.md b/animation-simulation/栈和队列/225.用队列实现栈.md index c6b17c8..ccaa942 100644 --- a/animation-simulation/栈和队列/225.用队列实现栈.md +++ b/animation-simulation/栈和队列/225.用队列实现栈.md @@ -18,6 +18,7 @@ 下面我们来看一下题目代码,也是很容易理解。 +Java Code: ```java class MyStack { //初始化队列 @@ -55,3 +56,34 @@ class MyStack { ``` +JS Code: +```javascript +var MyStack = function() { + this.queue = []; +}; + +MyStack.prototype.push = function(x) { + this.queue.push(x); + if (this.queue.length > 1) { + let i = this.queue.length - 1; + while (i) { + this.queue.push(this.queue.shift()); + i--; + } + } +}; + +MyStack.prototype.pop = function() { + return this.queue.shift(); +}; + +MyStack.prototype.top = function() { + return this.empty() ? null : this.queue[0]; + +}; + +MyStack.prototype.empty = function() { + return !this.queue.length; +}; +``` +