题目

模拟栈:数组实现 push/pop

思路

本题用数组实现栈的 push/pop,并处理栈满、栈空。 用 top 表示栈顶下标,空栈 top==-1。入栈前判满再 stack[++top]=x;出栈前判空再取 stack[top--]。

解题分析

栈顶 top,push 先 ++top 再写;pop 先读再 --top。判空 top<0,判满 top+1>=cap。

完整程序

import java.io.*;

public class Main {
    public static void main(String[] args) {
        int[] st = new int[32]; int top = -1;
        int op = 1;
        if (op == 1) {
            int x = 5;
            if (top + 1 < 32) st[++top] = x;
        }
        else if (op == 0) {
            if (top < 0) System.out.println("empty");
            else System.out.println(st[top--]);
        }
        int op = 1;
        if (op == 1) {
            int x = 3;
            if (top + 1 < 32) st[++top] = x;
        }
        else if (op == 0) {
            if (top < 0) System.out.println("empty");
            else System.out.println(st[top--]);
        }
        int op = 0;
        if (op == 1) {
            int x = -1;
            if (top + 1 < 32) st[++top] = x;
        }
        else if (op == 0) {
            if (top < 0) System.out.println("empty");
            else System.out.println(st[top--]);
        }
    }
}

运行示例

输出:

3