Java实现使用数组模拟栈

Java实现使用数组模拟栈,第1张

package 栈;

public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(3);
        System.out.println(arrayStack.isEmpty());
        arrayStack.push(1);
        arrayStack.push(2);
        arrayStack.push(3);
        System.out.println(arrayStack.isFull());
        arrayStack.show();
        System.out.println(arrayStack.pop());
    }
}

/**
 * 使用数组模拟栈,内部封装了对栈的各种 *** 作
 */
class ArrayStack {
    //定义数组存放栈
    private final int[] stack;
    private final int maxSize;
    private int top;

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
        top = -1;//指向栈顶元素,空栈时没有元素初始化为-1
    }

    /**
     * 判断栈满
     *
     * @return 是否栈满
     */
    public boolean isFull() {
        return top == maxSize - 1;
    }

    /**
     * 判断栈空
     *
     * @return 是否栈空
     */
    public boolean isEmpty() {
        return top == -1;
    }

    /**
     * 入栈
     *
     * @param value 值
     */
    public void push(int value) {
        if (isFull())
            throw new RuntimeException("栈满");
        stack[++top] = value;
    }

    /**
     * 出栈
     *
     * @return 出栈元素的值
     */
    public int pop() {
        if (isEmpty())
            throw new RuntimeException("栈空");
        return stack[top--];
    }

    /**
     * 显示当前栈内元素(栈顶->栈底)
     */
    public void show() {
        for (int i = top; i >= 0; i--) {
            System.out.print(stack[i] + "  ");
        }
        System.out.println();
    }

}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/871769.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存