Задача
Реализуйте очередь (FIFO), используя только два стека: push, peek, pop, empty.
Примеры
Пример 1
Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]
Explanation
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
Решение
Решение
var MyQueue = function() { this.input = []; // для push this.output = []; // для pop/peek }; MyQueue.prototype.push = function(x) { this.input.push(x); }; MyQueue.prototype.pop = function() { this.peek(); // переносим элементы если нужно return this.output.pop(); }; MyQueue.prototype.peek = function() { if (this.output.length === 0) { while (this.input.length > 0) { this.output.push(this.input.pop()); } } return this.output[this.output.length - 1]; }; MyQueue.prototype.empty = function() { return this.input.length === 0 && this.output.length === 0; };