题解 | #【模板】栈#

【模板】栈

https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
class Stack{
    constructor(x){
        this.x=x;
        this.arr=[]
    }
    push(x){
        return !isNaN(parseInt(x)) ? this.arr.push(x):console.log("输入整数")
    }
    pop(){
        return this.arr.length===0 ? 'error':this.arr.pop();
    }
    top(){
        let length=this.arr.length
        return this.arr.length===0 ? 'error':this.arr[length-1]
    }
}
let stack=new Stack()
let count=1;
let dataLine=[]
let n
void async function () {
    // Write your code here
    while(line = await readline()){
        dataLine.push(line)
        if(count==1){
            n=parseInt(dataLine[0])
        }
        
    }
    for(let i=1;i<=n;i++){
        if(dataLine[i].includes('push')){
            stack.push(dataLine[i].split(' ')[1])
        }else if(dataLine[i].includes('pop')){
            let numPop=stack.pop()
            console.log(numPop)
        }else if(dataLine[i].includes('top')){
            let numTop=stack.top()
            console.log(numTop)
        }
    }
}()

全部评论

相关推荐

老方子:英语等级cet写错了吧
点赞 评论 收藏
分享
01-16 18:34
四川大学 Java
欢迎加入AI:没有啥稳定不稳定,一切都源于业务快速发展还是收缩。我当年一开始去的央企,业务不赚钱,也贼卷,慢慢就开始优化了。。。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务