题目描述
请用栈实现一个队列,支持如下四种操作:
push(x) – 将元素x插到队尾;
pop() – 将队首的元素弹出,并返回该元素;
peek() – 返回队首元素;
empty() – 返回队列是否为空;
参考文献
JS代码
/**
* Initialize your data structure here.
*/
var MyQueue = function () {
this.stack = [];
this.helperStack = [];
};
/**
* Push element x to the back of queue.
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function (x) {
this.stack.push(x);
};
/**
* Removes the element from in front of queue and returns that element.
* @return {number}
*/
MyQueue.prototype.pop = function () {
while(this.stack.length > 0) {
this.helperStack.push(this.stack.pop());
}
let x = this.helperStack.pop();
while(this.helperStack.length > 0){
this.stack.push(this.helperStack.pop());
}
return x;
};
/**
* Get the front element.
* @return {number}
*/
MyQueue.prototype.peek = function () {
if (this.stack.length > 0) {
return this.stack[0];
} else {
return null;
}
};
/**
* Returns whether the queue is empty.
* @return {boolean}
*/
MyQueue.prototype.empty = function () {
return this.stack.length === 0;
};