225.用队列实现栈

用队列实现栈

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作。

解析

1
2
3
4
5
6
7
8
var MyStack = function () { this.queue = []; };
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());
};
MyStack.prototype.pop = function () { return this.queue.shift(); };
MyStack.prototype.top = function () { return this.queue[0]; };
MyStack.prototype.empty = function () { return this.queue.length === 0; };

225.用队列实现栈
https://leetcode.lz5z.com/225.implement-stack-using-queues/
作者
tickli
发布于
2024年7月10日
许可协议