114 阅读1分钟

什么是栈?

一个后进先出的数据结构 一个数组,push了元素a,b,这个过程叫入栈 pop 这个过程叫出栈,只能从数组末尾【栈顶】开始

实现

function Stack() {
  this.arr = [];

  //入栈
  this.push = (i) => {
    this.arr.push(i);
    return this.arr;
  };

  //出栈
  this.pop = () => {
      return this.arr.pop();
  }
}

例题

10进制转2进制

function fn1(index) {
  const arr = [];

  while (index > 0) {
    arr.push(index % 2);
    index = Math.floor(index / 2);
  }
  let str = "";
  while (arr.length > 0) {
    str += arr.pop();
  }

  return str;
}

函数调用

function fn3() {
  fn4();
  console.log("fn3");
}

function fn4() {
  console.log("fn4");
}

fn3();//fn4,fn3

有效括号

给定一个只包括 '('')''{''}''['']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
function fn1(str){
    if(str.length % 2 === 1){
        return false;
    }
    const arr = [];
    for(let i = 0;i < str.length; i++){
        const item = str[i];
        
        if(item === "(" || item === "{" || item ==="["){
            arr.push(item);
        }else{
            const top = arr[arr.length - 1];
            if(
                (top == "(" && item === ")")||
                (top == "[" && item === "]")||
                (top == "{" && item === "}")
            ){
                arr.pop()
            }else{
                return false;
            }
        }
    }

    return arr.length === 0;
}