《剑指Offer》JavaScript实战——用两个栈实现队列

    牛客网练习题传送门

题目描述

    用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题方法
let stack1=[],//两个数组模拟栈的行为
    stack2=[];
function push(node)
{
    // write code here
    //栈是后入先出(LIFO),队列是先入先出(FIFO)
    //模拟队列的push操作,直接往栈中推入即可
    //但是要考虑辅助栈中还存在值的情况,需要先将辅助栈中的值推回存储栈中
    while(stack2.length !== 0){
        stack1.push(stack2.pop());
    }
    stack1.push(node);
}
function pop()
{
    // write code here
    //模拟队列的pop操作则要考虑栈的后入先出特性,需要先将存储栈中的数组,推入辅助栈,然后辅助栈弹出
    while(stack1.length !== 0){
        stack2.push(stack1.pop());
    }
    return stack2.pop();
}
拓展——用两个队列实现一个栈的pop和push操作

    本质上和上面的没什么区别,只要抓住一点,栈是后入先出(LIFO),队列是先入先出(FIFO)。下面是实现代码。

let queue1=[],//两个数组模拟队列的行为
    queue2=[];
function push(node) {
    //推入的时候要判断哪个队列中有值,就推入那个队列中
    if(queue1.length === 0){
        queue2.push(node);
    }else{
        queue1.push(node);
    }
}

function pop() {
    //弹出的时候判断哪个队列中有值,则先将该队列中的n-1个值弹出并存入另一个队列中,然后弹出最后一个值则为结果
    if(queue1.length === 0){
        while(queue2.length !== 1){
            queue1.push(queue2.pop());
        }
        return queue2.pop();
    }else{
        while(queue1.length !== 1){
            queue2.push(queue1.pop());
        }
        return queue1.pop();
    }
}

猜你喜欢

转载自blog.csdn.net/sinat_36521655/article/details/80595143