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; +}; +``` +