* Initialize your data structure here.
*/
var MyQueue = function () {
this.s1 = [];
this.s2 = [];
this.top = null;
};
* Push element x to the back of queue.
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function (x) {
if (!this.s1.length) {
this.top = x;
}
this.s1.push(x);
};
* Removes the element from in front of queue and returns that element.
* @return {number}
*/
MyQueue.prototype.pop = function () {
if (this.s1.length <= 1) {
this.top = null;
}
while (this.s1.length > 1) {
this.top = this.s1.pop();
this.s2.push(this.top);
}
const pop = this.s1.pop();
while (this.s2.length) {
this.s1.push(this.s2.pop());
}
return pop;
};
* Get the front element.
* @return {number}
*/
MyQueue.prototype.peek = function () {
return this.top;
};
* Returns whether the queue is empty.
* @return {boolean}
*/
MyQueue.prototype.empty = function () {
return !this.s1.length;
};
评论