Java习题: 使用数组模拟栈数据结构

 

题目详见 B站 AV93347594 P88

大意为使用数组实现栈功能, 包括初始化栈、压栈、弹栈

 

实现代码

public class StackSim {
    Object[] ss;
    //int oLength;
    private int index = 0;

    public StackSim() {
    }

    public StackSim(int n) {
        ss = new Object[n];
        //oLength = ss.length;
    }

    public void push(Object o) {
        if (index == ss.length) {
            System.out.println("栈已满");
            return;
        }
        ss[index] = o;
        index += 1;
    }

    public void pop() {
        if (index == 0) {
            System.out.println("栈已空");
            return;
        }
        ss[index-1] = null;
        index -= 1;
    }
}

 

主要耗时花在了下标相关的逻辑处理

我是把下标默认设为 0 , 那么每次 压栈/弹栈 针对的都是当前栈帧, 动作执行先判断是否满足操作条件, 执行完成后对下标再进行移动操作

 

老杜在 P93 会给出他的答案, 他将下标默认设为 -1 , 压栈时则是 先移动下标, 再压入对象( 当然也可以像解答中所述写成一句, 使用 ++index )

 

完成后可以用测试程序来看下效果

public class Test {
    public static void main(String[] args) {
        StackSim s = new StackSim(3);
        s.push("One");
        s.push("Two");
        s.push(new Integer(9));
        System.out.println(s.ss[2]);

        s.push(new String("good"));
        System.out.println(s.ss[2]);

        s.pop();
        System.out.println(s.ss[s.ss.length-1]);
        s.pop();
        System.out.println(s.ss[s.ss.length-1]);
        s.pop();
        System.out.println(s.ss[s.ss.length-1]);
        s.pop();
        System.out.println(s.ss[s.ss.length-1]);
        s.pop();

    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值