5, java数据结构和算法: 栈 , 入栈, 出栈, 正序遍历,,逆序遍历

直接上代码:

  class ArrayStack{
    //用数组模拟栈
    int maxSize;
    int[] stack;
    int top = -1;//表示栈顶

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        this.stack = new int[maxSize];
    }

    //1, 入栈
    public void pushStack(int value){
        //判断是否满
        if(IsFull()){
            System.out.println("栈满了,不能添加");
            return;
        }
        top++;
        stack[top] = value;
    }

    //2, 出栈
    public int popStack() throws Exception {
        if(IsEmpty()){
            throw  new Exception("栈为空,不能出栈");
        }
        int value = stack[top];
        top--;
        return value;
    }
    //3. 栈的遍历
    public void show(){
        if(stack.length == 0){
            System.out.println("栈空,不能遍历");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.println(stack[i]);
        }

    }
    private boolean IsFull() {
        return top == maxSize-1;
    }
    private boolean IsEmpty(){
        return top == -1;
    }

    //4, 栈的逆序遍历
    public void resverShow(){
        if(stack.length == 0){
            System.out.println("栈空,不能遍历");
            return;
        }
        for (int i = 0; i <= top; i++) {
            System.out.println(stack[i]);
        }
    }
}

测试代码:

    public static void main(String[] args) throws Exception {
        ArrayStack stack = new ArrayStack(4);
        stack.pushStack(1);
        stack.pushStack(2);
        stack.pushStack(3);
        stack.pushStack(4);

        stack.show();//4-3-2-1  先进后出

        System.out.println("========");
        stack.popStack();
        stack.show();//3-2-1
        System.out.println("==========");
        stack.resverShow();//1-2-3
    }

测试结果:

posted @ 2020-05-31 21:55  死不了好气呦  阅读(389)  评论(0编辑  收藏  举报