题解 | #设计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]); } } });