js剑指offer-5-用两个栈实现队列

剑指offer5-用两个栈实现队列

题目描述

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

var stack1 = [];
var stack2 = [];
const push = node => stack1.push(node);
const pop = () => {
    let temp = stack1.pop();
    while(temp){
        stack2.push(temp);
        temp = stack1.pop();
    }
    const result = stack2.pop();
    temp = stack2.pop();
    while(temp){
        stack1.push(temp);
        temp = stack2.pop();
    }
    return result;
};

本题类型:队列、栈、数组

知识点:

  1. 队列:先进先出
  2. 栈:先进后出
  3. 箭头函数如果没有输入的参数,需用()代替,不能空着

解析:

  朴素的思路,将通过两个栈将队列顺序反转,得到队列的输出。

补充:其实一个数组也能实现队列,利用shift()方法

var stack1 = [];
const push = node => stack1.push(node);
const pop = () => stack1.shift();

猜你喜欢

转载自blog.csdn.net/julian_draxler/article/details/88070073