请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。int pop() 移除并返回栈顶元素。int top() 返回栈顶元素。boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
注意:
push to back、peek/pop from front、size 和 is empty 这些操作。
示例:
输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]
解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 Falsevar MyStack = function() {
this.queue = [];
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.queue.push(x);
//把前面的元素都移到后面,保留最后一个
for (let i = 0; i < this.queue.length - 1; i++) {
this.queue.push(this.queue.shift())
}
};
/**
* @return {number}
*/
MyStack.prototype.pop = function() {
return this.queue.shift();
};
/**
* @return {number}
*/
MyStack.prototype.top = function() {
return this.queue[0]
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return this.queue.length == 0;
};