数组模拟栈

数组模拟栈

public class Stack {
    Object[] objects=new Object[5];//创建一个数组
    int index=-1;//栈帧指向-1
    public void  push(Object o) throws StackException {//压榨方法
        if (index>=objects.length-1){ //当栈帧大于数组长度减一手动抛异常
            throw  new StackException("栈已满");
        }
        objects[++index]=o;//添加元素
        System.out.println("压榨"+o+"成功"+",栈帧指向"+index);
    }
    public void pop() throws StackException {//弹栈
        if(index<0){ //当栈帧小于0抛异常
            throw new StackException("栈已空");
        }
        //此处切记不能先将栈帧--,首先得弹出最顶端元素
        System.out.println("弹栈"+objects[index]+"成功"+"栈帧指向"+index);
        index--;
    }
}
public class StackException extends Exception {
    //自定义异常
    public StackException() {
    }

    public StackException(String s) {
        super(s);
    }
}
public class StackTest {
    public static void main(String[] args) throws StackException {
        Stack stack=new Stack();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        stack.push(6);
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
    }
}
//执行结果
//栈满
压榨1成功,栈帧指向0
压榨2成功,栈帧指向1
压榨3成功,栈帧指向2
压榨4成功,栈帧指向3
压榨5成功,栈帧指向4
Exception in thread "main" com.westore.stack.StackException: 栈已满
	at com.westore.stack.Stack.push(Stack.java:8)
	at com.westore.stack.StackTest.main(StackTest.java:11)
    
//栈空
Exception in thread "main" com.westore.stack.StackException: 栈已空
	at com.westore.stack.Stack.pop(Stack.java:15)
	at com.westore.stack.StackTest.main(StackTest.java:12)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值