完整代码实例-数组模拟栈的出入栈和打印输出(Java实现)

代码如下:

package DataStrcture.StackDemo;

import java.util.Scanner;

public class ArrToStack{
    ///定义数组以数组的大小, 类的构造方法
    ///注意 ! 在栈中我们规定top指针除了初始状态为-1外,其余时间都是指向栈顶最开头的那个数据
    int[] arr;
    int top = -1;//怎么能忘了栈的指针呢?
    int MAXSIZE;

    public ArrToStack(int size){
        this.MAXSIZE = size;
        arr = new int[MAXSIZE];
    }
    工具方法(判空和判满)
    public boolean isEmpty(){
        return top == -1;
    }

    public boolean isFull(){
        return top == MAXSIZE -1;
    }
    ///出栈和入栈主方法
    public void push(int num){
        //入栈要判满!
        if(isFull()){
            System.out.println("栈已经满啦! num "+num+"放不进去啦!");
            return;
        }
        top++;
        arr[top] = num;
        System.out.println("入栈成功! ");
    }
    public int pop(){
        ///出栈要判空!
        if(isEmpty()){
            throw new RuntimeException("当前栈已经空了,无法继续取元素了! ");
        }
        int val = arr[top];
        top--;
        return val;
    }
    遍历并输出栈的内容
    public void list(){
        if(isEmpty()){
            throw new RuntimeException("当前栈已经空了,无法继续取元素了!");
        }
        for (int i=top; i >=0; i--){
            System.out.println(arr[i]);
        }
    }

    public static void main(String[] args) {
        ArrToStack stack = null;
        Scanner scanner = new Scanner(System.in);


        while(true){

            System.out.printf("\t ===============菜单=================\n");
            System.out.printf("\t 请输入下面指令执行程序: \n");
            System.out.printf("\t a: 指定栈的长度并对栈进行初始化 \n" );
            System.out.printf("\t b: 往栈中插入数据 \n" );
            System.out.printf("\t c: 出栈一个元素 \n" );
            System.out.printf("\t d: 直接打印出栈中的所有内容 \n" );
            System.out.printf("\t e: 退出程序 \n" );
            System.out.printf("\t ====================================\n");

            char res = scanner.next().charAt(0);
            switch(res){
                case 'a':
                    System.out.println("请输入栈的长度: ");
                    int size = scanner.nextInt();
                    stack = new ArrToStack(size);
                    System.out.println("栈初始化完成! ");
                    break;

                case 'b':
                    System.out.println("请输入要压入栈中的数字: ");
                    int num = scanner.nextInt();
                    stack.push(num);

                    break;

                case 'c':
                    System.out.println("当前出栈的元素为: "+stack.pop());
                    break;

                case 'd':
                    System.out.println("栈中的元素如下: ");
                    stack.list();
                    break;

                case 'e':
                    System.out.println("程序已退出 ");
                    System.exit(0);
            }
        }

    }
}

运行结果:

在这里插入图片描述

posted @ 2022-05-26 20:31  青松城  阅读(53)  评论(0编辑  收藏  举报