11栈
先进后出
例题–蓝桥19877
用数组来设置栈
1.向栈顶插入元素--top位置标记元素
2.删除栈顶元素--top指针减减
3.输出栈顶元素--输出top位置元素
使用arraylist
import java.util.ArrayList;
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner sc=new Scanner(System.in);ArrayList<Integer> array=new ArrayList<>();int m=sc.nextInt();for (int i = 0; i < m; i++){String str=sc.next();switch (str){case "push":int x=sc.nextInt();array.add(x);break;case "pop":if (array.size()==0){break;}else {array.remove(array.size()-1);}break;case "empty":if (array.size()==0){System.out.println("YES");}else {System.out.println("NO");}break;case "query":if (array.size()==0){System.out.println("empty");}else {System.out.println(array.get(array.size()-1));}break;default:System.out.println("error");}}}}
使用数组
import java.io.*;
import java.util.*;
import java.math.BigInteger;public class Main {static int N = (int)(1e5+10);static int[] stk = new int[N];static int top = 0;static void push(int x) {stk[++top] = x;}static void pop() {if(isEmpty()) return;top--;}static boolean isEmpty() {return top==0;}static void query() {if(isEmpty()) out.println("empty");else out.println(stk[top]);}static void solve() {int m = in.nextInt();while(m-->0) {String op = in.next();if(op.equals("push")) {int x = in.nextInt();push(x);}else if(op.equals("pop")) {pop();}else if(op.equals("empty")) {out.println(isEmpty()?"YES":"NO");}else {query();}}}public static void main(String[] args) {solve();out.flush();}static FastReader in = new FastReader();static PrintWriter out = new PrintWriter(System.out);static class FastReader {static BufferedReader br;static StringTokenizer st;FastReader() {br = new BufferedReader(new InputStreamReader(System.in));}String next() {String str = "";while(st==null||!st.hasMoreElements()) {try {str = br.readLine();}catch(IOException e) {throw new RuntimeException(e);}st = new StringTokenizer(str);}return st.nextToken();}int nextInt() {return Integer.parseInt(next());}double nextDouble() {return Double.parseDouble(next());}long nextLong() {return Long.parseLong(next());}}
}