55 阅读1分钟
  • 先进后出
  • 这里用数组来模拟栈

模板

  • C++
// tt表示栈顶
int stk[N], tt = 0;

// 向栈顶插入一个数
stk[ ++ tt] = x;

// 从栈顶弹出一个数
tt -- ;

// 栈顶的值
stk[tt];

// 判断栈是否为空,如果 tt > 0,则表示不为空
if (tt > 0)
{

}

练习

01 模拟栈

  • 题目

Snipaste_2023-03-01_22-45-52.png

  • 题解
import java.io.*;

public class Main {
    public static final int N = 100010;
    public static int stk[] = new int[N];
    public static int tt = 0;
    public static int M;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        M = Integer.parseInt(br.readLine());

        while (M-- > 0) {
            String[] str1 = br.readLine().split(" ");
            if (str1[0].equals("push")) {
                stk[++tt] = Integer.parseInt(str1[1]);
            } else if (str1[0].equals("pop")) {
                tt--;
            } else if (str1[0].equals("empty")) {
                if (tt > 0) {
                    pw.println("NO");
                } else {
                    pw.println("YES");
                }
            } else {
                pw.println(stk[tt]);
            }
        }

        pw.close();
        br.close();
    }
}

02 表达式求值

还没做,等做了再更