栈和队列如何互相实现呢?

今天只是来按照惯例来进行常规的刷题:

主要是复习栈和队列的基础实现,可能会稍稍有一点难度,让我们开始吧:

image.png

实现思路:

其实用栈去实现队列的时候,需要注意的是两者的性质;先进后出如何去维护一个先进先出的结构呢?好好想想,一个栈似乎做不到,那么如果是两个栈,一个维护进队的操作,一个维护出队的操作是不是就可以了呢?

代码实现:

var MyQueue = function() {
    this.stack1 = [];
    this.stack2 = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this.stack1.push(x);
};

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    // 少了一步 如果 stackOut 有值 该怎么办呢
    // 执行this.pop 的时候会依次把 this.stack1中值放到this.stack2中
    const size = this.stack2.length;
    if (size) return this.stack2.pop();
    while(this.stack1.length) {
        this.stack2.push(this.stack1.pop());
    }
    return this.stack2.pop();
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    let temp = this.pop();
    this.stack2.push(temp);
    return temp;
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return this.stack1.length === 0 && this.stack2.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()
 */
复制代码

image.png

image.png

实现思路:

其实这里针对于代码实现的分析: 用队列去实现栈的时候,需要注意的点在于如何将先进的元素变为后出;后进的元素先出; 这里的实现不会多么的复杂,需要想在队列中去拿最后一个元素变为第一个元素需要如何去实现? 如果没有想法可以参考一下我的代码实现。

代码实现:

var MyStack = function() {
    this.queue1 = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function(x) {
    this.queue1.push(x);
};

/**
 * @return {number}
 */
MyStack.prototype.pop = function() {
    let size = this.queue1.length;
    // 将队头的元素取出来 依次添加到队尾 只剩下最后一个元素
    while(size-- > 1) {
        this.queue1.push(this.queue1.shift())
    }
    return this.queue1.shift();
};

/**
 * @return {number}
 */
MyStack.prototype.top = function() {
    let temp = this.pop();
    this.queue1.push(temp);
    return temp;
};

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

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

复制代码

232.用栈实现队列

225. 用队列实现栈

猜你喜欢

转载自juejin.im/post/7061965554659098654