跳至主要內容

Mr.He小于 1 分钟

var MyStack = function() {
    // 模拟队列,只能使用 push(入队) 和 shift(出队)
    this.queue = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function(x) {
    // 1. 新元素入队
    this.queue.push(x);
    
    // 2. 将新元素前面的所有元素依次取出并重新放入队尾
    // 这样能保证新元素始终在队首(模拟栈顶)
    const size = this.queue.length;
    for (let i = 0; i < size - 1; i++) {
        // shift() 模拟从队头出队,push() 模拟入队
        this.queue.push(this.queue.shift());
    }
};

/**
 * @return {number}
 */
MyStack.prototype.pop = function() {
    // 由于 push 时已经调整过顺序,队头就是栈顶元素
    return this.queue.shift();
};

/**
 * @return {number}
 */
MyStack.prototype.top = function() {
    // 查看队头元素
    return this.queue[0];
};

/**
 * @return {boolean}
 */
MyStack.prototype.empty = function() {
    return this.queue.length === 0;
};