题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
import java.util.Scanner fun main(args: Array<String>) { val read = Scanner(System.`in`) val size = read.nextLine().toInt() val stackAb1 = StackAb1(size) while (read.hasNextLine()) { val lineArr = read.nextLine().split(" ") if (lineArr[0] == "push") { stackAb1.push(lineArr[1].toInt()) } else if (lineArr[0] == "pop") { stackAb1.pop() } else { stackAb1.top() } } } class StackAb1(size: Int) { private lateinit var tempArray: IntArray private var top = 0 init { if (size in 1..100000) { tempArray = IntArray(size) } else { println("error") } } fun push(value: Int) { if (top < tempArray.size) { tempArray[++top] = value } else { println("error") } } fun pop() { if (top > 0) { println(tempArray[top--]) } else { println("error") } } fun top() { if (top > 0) { println(tempArray[top]) } else { println("error") } } }