232.用栈实现队列

var Stack = function() {
    this.stack = []
}
Stack.prototype.push = function(val) {
    this.stack.push(val)
}
Stack.prototype.pop = function() {
    return this.stack.pop()
}
Stack.prototype.size = function() {
    return this.stack.length
}
Stack.prototype.empty = function() {
    return this.stack.length === 0
}

/**
 * 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
 */
var MyQueue = function() {
    this.stack1 = new Stack() // 储存原始数据
    this.stack2 = new Stack() // 遍历原始数据时用来临时储存数据
};

/** 
 * 将元素 x 推到队列的末尾
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this.stack1.push(x)
};

/**
 * 从队列的开头移除并返回元素
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    // 队列的开头就是栈底
    // 临时储存到stack2
    while(this.stack1.size() > 0) {
        this.stack2.push(this.stack1.pop())
    }
    // 删除stack1栈底元素,也就是stack2的栈顶
    let element = this.stack2.pop()
    // 再把数据放回stack1
    while(this.stack2.size() > 0) {
        this.stack1.push(this.stack2.pop())
    }
    
    return element
};

/**
 * 返回队列头元素
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    // 实际上是返回栈底元素
    let element
    // 临时储存到stack2
    while(this.stack1.size() > 0) {
        this.stack2.push(this.stack1.pop())
    }
    element = this.stack2.pop()

    // 再把数据从stack2放回stack1
    this.stack2.push(element)
    while(this.stack2.size() > 0) {
        this.stack1.push(this.stack2.pop())
    }

    return element
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return this.stack1.size() === 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()
 */

let 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