数据结构(二):一个数组固定分割实现三个栈

//一个数组固定分割实现三个栈
public class StackByArray {
    //栈大小
    int stackSize = 100;
    //三个栈的栈顶指针
    int[] stactTopOfStack = {-1,-1,-1};
    //存放数据的数组
    int[] theArray = new int[stackSize*3];
    //入栈方法
    void push(int stackNum,int x){
        if (stactTopOfStack[stackNum]+1>stackSize){
            return;
        }
        //栈顶指针自增,然后更新栈顶元素
        stactTopOfStack[stackNum]++;
        theArray[topOfStack(stackNum)]=x;
    }
    //出栈方法
    int pop(int stackNum) throws Exception{
        if (stactTopOfStack[stackNum]==-1){
            throw new Exception("栈是空的,无法出栈");
        }
        //获取栈顶的元素,并将栈顶位置清零,同时指针自减
        int value = theArray[topOfStack(stackNum)];
        theArray[topOfStack(stackNum)] = 0;
        stactTopOfStack[stackNum]--;
        return value;
    }

    int top(int stackNum) throws Exception{
        if (stactTopOfStack[stackNum]==-1){
            throw new Exception("栈是空的,无法获得栈顶元素");
        }
        return theArray[topOfStack(stackNum)];
    }

    /*返回索引为stackNum栈的栈顶元素,在数组中的索引*/
    int topOfStack(int stackNum){
        return stackSize * stackNum + stactTopOfStack[stackNum];
    }

    public static void main(String[] args) {
        StackByArray stack = new StackByArray();
        //向第一个栈插入数据
        stack.push(0, 1);
        stack.push(0, 2);
        //向第二个栈插入数据
        stack.push(1, 3);
        stack.push(1, 4);
        //向第三个栈插入数据
        stack.push(2, 5);
        stack.push(2, 6);
        try {
            System.out.println(stack.pop(0));
            System.out.println(stack.top(0));
            System.out.println(stack.pop(0));
            System.out.println(stack.pop(0));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值