请你仅使用两个队列实现一个后入先出(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; };
|