[路飞]_算法成长之路二十四,化栈为队

95 阅读1分钟

个人算法成长之路二十四!!!定期更新一些刷题过程中个人的思路以及理解。有兴趣的朋友们可以互动交流哈~

题目:

leetcode-面试题 03.04. 化栈为队

实现一个MyQueue类,该类用两个栈来实现一个队列。 示例:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek();  // 返回 1
queue.pop();   // 返回 1
queue.empty(); // 返回 false

解题思路:

var MyQueue = function() {
    this.stackIn = [];
    this.stackOut = [];
};

MyQueue.prototype.push = function(x) {
    this.stackIn.push(x);
};

MyQueue.prototype.pop = function() {
    while(this.stackIn.length > 1){
        this.stackOut.push(this.stackIn.pop());
    }
    let ans =  this.stackIn.pop();
    while(this.stackOut.length){
        this.stackIn.push(this.stackOut.pop());
    }
    return ans;
};

MyQueue.prototype.peek = function() {
    while(this.stackIn.length){
        this.stackOut.push(this.stackIn.pop());
    }
    let ans =  this.stackOut[this.stackOut.length - 1];
    while(this.stackOut.length){
        this.stackIn.push(this.stackOut.pop());
    }
    return ans;
};

MyQueue.prototype.empty = function() {
    return !this.stackIn.length && !this.stackOut.length;
};