用栈来模拟一个队列,要求实现队列的两个基本操作:入队、出队。

既然我们拥有两个栈,那么可以让其中一个栈作为队列的入口,负责插入新元素;另一个栈作为队列的出口,负责移除老元素。



队列的主要操作无非有两个:入队和出队。
在模拟入队操作时,每一个新元素都被压入到栈 A 当中。
让元素 1 入队。

让元素 2 入队。

让元素 3 入队。

这时,我们希望最先入队的元素1出队,需要怎么做呢?
让栈 A 中的所有元素按顺序出栈,再按照出栈顺序压入栈 B。这样一来,元素从栈 A 弹出并压入栈 B 的顺序是 3、2、1,和当初进入栈 A 的顺序 1、2、3 是相反的。

此时让元素 1 出队,也就是让元素 1 从栈 B 中弹出。
让元素 2 出队。

让元素 4 入队。

此时出队操作仍然从栈 B 中弹出元素。
让元素 3 出队。


让元素 4 出队。
/*** Initialize your data structure here.*/var MyQueue = function() {this.input = []this.output = []};/*** Push element x to the back of queue.* @param {number} x* @return {void}*/MyQueue.prototype.push = function(x) {this.input.push(x)};/*** Removes the element from in front of queue and returns that element.* @return {number}*/MyQueue.prototype.pop = function() {if(!this.output.length) {while(this.input.length) {this.output.push(this.input.pop())}}return this.output.pop()};/*** Get the front element.* @return {number}*/MyQueue.prototype.peek = function() {if(!this.output.length) {while(this.input.length) {this.output.push(this.input.pop())}}return this.output[this.output.length - 1]};/*** Returns whether the queue is empty.* @return {boolean}*/MyQueue.prototype.empty = function() {if(this.input.length || this.output.length){return false} else{return true}};/*** 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()*/
