Java顺序栈(数组实现)

顺序栈可以使用数组实现一下,代码如下

package;
public class StackOrder {
    
     // 顺序栈
    static int curr = -1; // 指向栈底
    static int[] stack = new int[10];
    public static void main(String[] args) {
    
    
        push(1);
        push(2);
        pop();
        pop();
        pop();
    }
    public static void push(int data) {
    
    
        if (curr++ < 9) // 判断栈是否满了
            stack[curr] = data; //入栈
        else
            System.out.println("out of stack");
    }
    public static void pop() {
    
    
        if (curr > -1) {
    
     // 判断栈是否为空
            System.out.println(stack[curr]); // 出栈
            curr--;
        }
        else
            System.out.println("null");
    }
}

运行结果如下

2
1
null

猜你喜欢

转载自blog.csdn.net/qq_35712788/article/details/104737630