剑指offer_用两个栈实现队列

155 阅读1分钟

题目链接:www.acwing.com/problem/con…

分析

栈 后进先出, 队列 先进先出

  1. js种栈直接用数组即可
  2. 压入,直接A栈压入
  3. 弹出,全部弹出压入到辅助栈,弹出一个,再压回A栈
  4. peek 检测A[0]
  5. 是否为空 A.length === 0

Code

/**
 * Initialize your data structure here.
 */
var MyQueue = function() {
    this.stackA = [];
    this.stackB = [];
};

/**
 * Push element x to the back of queue. 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this.stackA.push(x);    
};

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    while(this.stackA.length > 0){
        this.stackB.push(this.stackA.pop());
    }
    let x = this.stackB.pop();
    while(this.stackB.length > 0){
        this.stackA.push(this.stackB.pop());
    }
    return x;
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    if(this.stackA.length > 0) return this.stackA[0];
    else return null;
};

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return this.stackA.length === 0;
};

/** 
 * Your MyQueue object will be instantiated and called as such:
 * var obj = new MyQueue();
 * obj.push(x);
 * var param_2 = obj.pop();
 * var param_3 = obj.peek();
 * var param_4 = obj.empty();
 */