0
点赞
收藏
分享

微信扫一扫

用java模拟栈,进栈出栈(压栈、弹栈)

扬帆远航_df7c 2022-03-18 阅读 39
javaidea

题目说明:

1、这个栈可以存储java中任何引用类型的数据

2、在栈中提供push方法模拟压栈

3、使用pop方法模拟弹栈

4、栈满了或者空了要有提示信息

5、默认初始容量为10;

6、编写测试程序模拟压栈弹栈

栈类代码如下:

public class Stack {
    //数组
    private Object[] sta;
    //栈帧
    private int index;

    //无参构造方法
    public Stack() {
        //默认容量为10
        this.sta=new Object[10];
        //栈帧初始化为-1;
        this.index=-1;
    }
    //set和get方法
    public Object[] getSta() {
        return sta;
    }

    public void setSta(Object[] sta) {
        this.sta = sta;
    }

    public Stack(int index) {
        this.index = index;
    }

    //压栈方法
    public void push(Object o){
        //判断栈是否满了
        if (this.index>=this.sta.length-1){
            System.out.println("栈已满!压栈失败!");
            return;
        }
        //栈未满栈帧加一
        this.index++;
        //压栈
        this.sta[index]=o;
        System.out.println(this.sta[index]+"压栈成功!栈帧指向:"+this.index);
    }
    //弹栈方法
    public void pop(){
        if(this.index<0){
            System.out.println("栈已空!弹栈失败!");
            return;
        }
        System.out.print(this.sta[index]+"弹栈成功!");
        this.index--;
        System.out.println("栈帧指向"+this.index);
    }
}

测试类代码:

public class Text {
    public static void main(String[] args) {

        Stack s=new Stack();
        //循环创建对象压栈
        for (int i = 0; i < 11; i++) {
            s.push(new Object());
        }
        //循环创建对象弹栈
        for (int i = 0; i < 11; i++) {
            s.pop();

        }

    }
}

运行结果如下:

 

 

举报

相关推荐

0 条评论