题解 | #设计getMin功能的栈#

设计getMin功能的栈

https://www.nowcoder.com/practice/05e57ce2cd8e4a1eae8c3b0a7e9886be

// 使用数组作为栈的结构,满足后进先出即可,js要注意比较的时候转换为整数,命令行输入默认是字符串在比较的时候会出问题。如果有发现stackMin压不进数,就去检查入栈条件是否加了parseInt
class stack {
  constructor() {
    this.stackData = [];
    this.stackMin = [];
  }
  push(newNum) {
    if (this.stackMin.length == 0) {
      this.stackMin.unshift(newNum);
    } else if (parseInt(newNum) <= this.getMin()) {
      this.stackMin.unshift(newNum);
    }

    this.stackData.unshift(newNum);
  }
  pop(){
      if(this.stackData.length==0){
          throw "Your stack is empty"
      }
      let value= this.stackData.shift();
      if(value==this.getMin()){
          this.stackMin.shift();
      }
      return value;
  }

  getMin() {
    if (this.stackMin.length == 0) {
      throw "Your stack is empty";
    }
    return this.stackMin[0];
  }
}

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let stack1 =new stack()
let step1=0;
let res =[];
let step2=0;
rl.on("line", function (line) {

  const tokens = line.split(" ");
  if(tokens.length==1&&step2==0){
    step2 = tokens[0];
  }else{
      if(tokens[0]==='push'){
          stack1.push(tokens[1]);
      }
      if(tokens[0]==='getMin'){
          res.push(stack1.getMin());
      }
      if(tokens[0]==='pop'){
          stack1.pop();
      }
      step1++;
  }
    if(step1==step2){
        for(let i=0;i<res.length;i++){
            console.log(res[i]);
        }
    }
});

全部评论

相关推荐

点赞 评论 收藏
分享
02-05 08:18
四川大学 Java
在思考的熊熊很讨厌吃香菜:不是,我门头沟学院呢?这都没排上?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务