题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
import java.util.*; class Stack1{ int maxSize ; int size = 0 ; int top = 0 ; int[] data ; public Stack1(int maxSize){ this.maxSize = maxSize ; this.data = new int[maxSize] ; } public void push(int x){ if(this.size == this.maxSize){ System.out.println("error") ; }else{ data[this.top++] = x ; this.size++; } } public void pop(){ //出栈 if(this.size == 0){ System.out.println("error"); }else{ System.out.println(data[--this.top]); this.size-- ; } } public void top(){ //输出栈顶元素 if(this.size == 0){ System.out.println("error"); }else { System.out.println(data[top - 1 ]); } } } public class Main{ public static void main(String[] args){ Scanner s = new Scanner(System.in) ; int n = Integer.parseInt(s.nextLine()); Stack1 q = new Stack1(n); while(s.hasNextLine()){ String str = s.nextLine(); String[] arr = str.split(" "); if(arr[0].equals("push")){ q.push(Integer.parseInt(arr[1])) ; }else if(arr[0].equals("pop")){ q.pop() ; }else{ q.top() ; } } } }