代码随想录算法训练营第十天 | ● 理论基础 ● 232.用栈实现队列 ● 225. 用队列实现栈

发布时间 2023-11-19 20:58:21作者: 李家成

今日学习的文章链接和视频链接

● 232.用栈实现队列


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

};

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

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    if(this.stackOut.length){
        return this.stackOut.pop()
    }
    console.log(this)
    while(this.stackIn.length){
        this.stackOut.push(this.stackIn.pop())
    }
    // console.log(this)
    return this.stackOut.pop()
};

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

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    // console.log(this.stackIn.length,this.stackOut.length)
    return !this.stackIn.length&&!this.stackOut.length

};

/**
 * 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()
 */

● 225. 用队列实现栈


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

};

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

/**
 * @return {number}
 */
MyStack.prototype.pop = function() {
    if(!this.stackIn.length){
        [this.stackIn,this.stackOut] = [this.stackOut , this.stackIn];
    }
    while(this.stackIn.length>1){
        this.stackOut.push(this.stackIn.shift());
    }
    return this.stackIn.shift()

};

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


};

/**
 * @return {boolean}
 */
MyStack.prototype.empty = function() {
    return !this.stackIn.length&&!this.stackOut.length

};

/**
 * 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()
 */

今日收获,记录一下自己的学习时长

1h