用数组内实现两个栈(JAVA)

问题

如何只用一个数组实现两个栈?并且保证只要数组中海油剩余空间,不抛出异常

思路

1.初始化两个下标变量分别指向数组的左右两端
2.左边的下标指示第一个栈,右边的下标指示第二个栈
3.如果需要对第一个栈执行元素入栈操作,那么将元素赋值到左边下标变量指示的位置
4.如果需要对第二个栈执行元素入栈操作,那么将元素赋值到右边下标变量指示的位置
5.第一个栈向右增长,第二个栈向左增长

代码

/**
 * 使用一个数组实现两个栈
 * 栈和数组综合考察
 */
public class ArrayWithTwoStacks {

    /*
    元数据数组
     */
    private int[] dataArray;

    /*
    数组容量
     */
    private int size;

    /*
    概念栈StackId=1的栈的指针
     */
    private int topOne;

    /*
    概念栈StackId=1的栈的指针
     */
    private int topTwo;

    public ArrayWithTwoStacks(int size) {
        //两个栈存在的边界条件size>=2
        if (size < 2) {
            throw new IllegalStateException("size < 2 is no persmissible");
        }
        dataArray = new int[size];
        this.size = size;
        topOne = -1;
        topTwo = size;
    }

    /**
     * 入栈操作
     *
     * @param stackId
     * @param data
     */
    public void push(int stackId, int data) {
        //是否满栈
        if (topOne + 1 == topTwo) {
            throw new IllegalStateException("Array is full!");
            //可以参入数组扩容操作,对当前数组现有元素进行重编,初始化栈指针
        }
        if (stackId == 1) {
            dataArray[++topOne] = data;
        } else if (stackId == 2) {
            dataArray[--topTwo] = data;
        } else {
            return;
        }
    }

    /**
     * 出栈
     *
     * @param stackId
     * @return
     */
    public int pop(int stackId) {
        if (stackId == 1) {
            if (topOne == -1) {
                throw new EmptyStackException();
            }
            return dataArray[topOne--];
        } else {
            if (topTwo == size) {
                throw new EmptyStackException();
            }
            return dataArray[topTwo++];
        }
    }

    /**
     * 栈顶元素
     *
     * @param stackId
     * @return
     */
    public int top(int stackId) {
        if (stackId == 1) {
            if (topOne == 1) {
                throw new EmptyStackException();
            }
            return dataArray[topOne];
        } else {
            if (topTwo == this.size) {
                throw new EmptyStackException();
            }
            return dataArray[topTwo];
        }
    }

    /**
     * 栈非空
     *
     * @param stackId
     * @return
     */
    public boolean isEmpty(int stackId) {
        if (stackId == 1) {
            return topOne == -1;
        } else if (stackId == 2) {
            return topTwo == this.size;
        } else {
            return true;
        }
    }


}

两个栈的push(入栈)和pop(出栈)操作的时间复杂度都为O(1),空间复杂度为O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值