请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(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操作是合法的。 - 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。 示例 1:
输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]
解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
提示:
1 <= x <= 9- 最多调用
100次push、pop、peek和empty - 假设所有操作都是有效的 (例如,一个空的队列不会调用
pop或者peek操作)
题解:
// 方法一:通过两个栈结构处理
var MyQueue = function () {
this.stack = []
this.helpStack = []
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function (x) {
this.helpStack.push(x)
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function () {
// 判断如果主栈内有数据,说明已经从辅助栈内把数据翻转过
if (this.stack.length) {
return this.stack.pop()
}
// 为反转数据时,遍历辅助栈,把辅助栈内数据翻转至主栈内
// 数据翻转,此时通过栈的pop()操作等同于队列的shift()操作
while (this.helpStack.length) {
this.stack.push(this.helpStack.pop())
}
return this.stack.pop()
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function () {
// 判断是否做了数据翻转,翻转了取主栈的最后一条数据
// 未翻转取辅助栈内第一条数据
if (this.stack.length) {
return this.stack[this.stack.length - 1]
} else {
return this.helpStack[0]
}
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function () {
// 判断如果主站或者辅助栈内有数据返回false
return !(this.stack.length || this.helpStack.length);
};
/**
* 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()
*/
// 方法二:通过赋值以及es6方式(不符合题意)
var MyQueue = function () {
this.stack = []
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function (x) {
// 根据数的length来赋值
this.stack[this.stack.length] = x
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function () {
// 通过es6的结构方式,获取到第一位进站的元素,
// 修改stack的数据
let [top, ...arr] = this.stack
this.stack = arr
return top
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function () {
return this.stack[0]
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function () {
return this.stack.length == 0
};