请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾int pop() 从队列的开头移除并返回元素int peek() 返回队列开头的元素boolean empty() 如果队列为空,返回 true ;否则,返回 false说明:
push to top, peek/pop from top, size, 和 is empty 操作是合法的。这道题可以理解用栈实现队列的操作,正常push,可队列是从队列的头部弹出元素,比如shift()方法,但是对于栈只有pop(),从队尾弹出
但是不可以直接使用shift(),相当于用栈的方法来模拟
var MyQueue = function() {
this.stackIn = [];
this.stackOut = [];
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.stackIn.push(x);
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function() {
if (!this.stackOut.length) {
while(this.stackIn.length) {
this.stackOut.push(this.stackIn.pop())
}
}
return this.stackOut.pop();
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
if (!this.stackOut.length) {
while(this.stackIn.length) {
this.stackOut.push(this.stackIn.pop())
}
}
return this.stackOut[this.stackOut.length - 1];
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return this.stackOut.length == 0 && this.stackIn.length == 0
};