题解 | #【模板】栈#
【模板】栈
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; void async function () { class Stack { #pointer = -1 // 栈顶指针,栈空时为-1 constructor() { this.items = [] // 用js数组存储数据,原始为动态容量 } push(x) { this.items[++this.#pointer] = x // 进栈 } pop() { if(!this.isEmpty()) { return this.items[this.#pointer--] // 出栈 } else { return 'error' } } top() { if(!this.isEmpty()) { return this.items[this.#pointer] // 取栈顶元素 } else { return 'error' } } isEmpty() { return this.#pointer === -1 // 判空 } } const stack = new Stack() while(line = await readline()){ const arr = line.split(' ') if(arr[0] === 'push') { stack.push(arr[1]) } if(arr[0] === 'pop') { console.log(stack.pop()) } if(arr[0] === 'top') { console.log(stack.top()) } } }()#js#