剑指OfferJZ5 用两个栈实现队列(JavaScript:栈)

时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M 热度指数:793593
本题知识点: 栈

题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

思路:
注意审题,用两个栈实现

在这里插入图片描述

let inStack = [],
    outStack = []

function push(node) {
    
    
    inStack.push(node)
}

function pop() {
    
    
    if (outStack.length) return outStack.pop()
    else {
    
    
        while (inStack.length) {
    
    
            outStack.push(inStack.pop())
        }
        return outStack.pop()
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44523860/article/details/114538378