代码随想录训练营day10

62 阅读1分钟

用栈实现队列

题目链接:用栈实现队列

  • 一个数入栈 & 一个输出栈
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()
    while(this.stackIn.length) {
        this.stackOut.push(this.stackIn.pop())
    }
    return this.stackOut.pop()
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    const node = this.pop()
    this.stackOut.push(node)
    return node
};

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

用队列实现栈

题目链接:用队列实现栈

  • 一个栈就可以实现
var MyStack = function() {
    this.queue = []
};

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

/**
 * @return {number}
 */
MyStack.prototype.pop = function() {
    return this.queue.pop()
};

/**
 * @return {number}
 */
MyStack.prototype.top = function() {
    const node = this.pop()
    this.push(node)
    return node
};

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