232.用栈实现队列

用栈实现队列

请你仅使用两个栈实现先入先出队列。

解析

1
2
3
4
5
6
7
8
var MyQueue = function () { this.inStack = []; this.outStack = []; };
MyQueue.prototype.push = function (x) { this.inStack.push(x); };
MyQueue.prototype.pop = function () { this._transfer(); return this.outStack.pop(); };
MyQueue.prototype.peek = function () { this._transfer(); return this.outStack[this.outStack.length - 1]; };
MyQueue.prototype.empty = function () { return !this.inStack.length && !this.outStack.length; };
MyQueue.prototype._transfer = function () {
if (!this.outStack.length) while (this.inStack.length) this.outStack.push(this.inStack.pop());
};

232.用栈实现队列
https://leetcode.lz5z.com/232.implement-queue-using-stacks/
作者
tickli
发布于
2024年7月17日
许可协议