题解 | #用两个栈实现队列#

用两个栈实现队列

https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6

/**
1. s1存储每次push的node
2. pop时,需要拿到s1最底下的node,需要s2辅助
3. s2存储s1pop的值直到s1为空栈,这样顺序就反过来了
4. s2在pop就模拟出了队列
*/

let s1 = []
let s2 = []
function push(node)
{
    s1.push(node)
}
function pop()
{
    // write code here
    if(!s2.length){
        while(s1.length){
            s2.push(s1.pop())
        }
    }
    return s2.pop()
}
module.exports = {
    push : push,
    pop : pop
};

全部评论

相关推荐

鼗:学校那里北改成中,学院改成大学 再放大以及加粗就行
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务