解释: 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
/** * Initialize your data structure here. */ var MyQueue = function() { this.input = []; this.output = []; };
/** * Push element x to the back of queue. * @param {number}x * @return {void} */ MyQueue.prototype.push = function(x) { this.input.push(x); };
/** * Removes the element from in front of queue and returns that element. * @return {number} */ MyQueue.prototype.pop = function() { this.peek(); returnthis.output.pop(); };
/** * Get the front element. * @return {number} */ MyQueue.prototype.peek = function() { if (this.output.length === 0) { while (this.input.length > 0) { this.output.push(this.input.pop()); } } returnthis.output[this.output.length - 1]; };