Java实现栈-两栈共享空间

大话数据结构中以合租房子为例,来比喻两栈共享空间这种结构,我想说得已经比较清楚了,在Java实现中,我们定义一个数组作为基准存储容器,两个栈,栈1的栈底是在数组的始端,栈2的栈底在数组的顶端,两个栈在push元素时候主键朝数组的中间靠拢,当栈1的栈顶top1+1=栈2 栈顶top2,那么此时栈满;

下面上代码:

public class BothStackShareMemory {

    private Object[] array;//定义一个数组存储

    private int stackSize;//栈长度

    private int top1;//第一个栈的栈顶指针

    private int top2;//第2个栈的栈顶指针

    /**
     * 初始化构建栈
     */
    public BothStackShareMemory() {
        stackSize = 10;
        array = new Object[stackSize];
        top1 = -1;
        top2 = stackSize;//都是空栈
    }

    /**
     * 压栈
     *
     * @param stackNum
     * @param element
     * @return
     */
    public boolean push(int stackNum, Object element) {
        if (top1 + 1 == top2) {
            System.out.println("栈满");
            return false;
        }
        if (stackNum == 1) {
            top1++;
            array[top1] = element;
        } else {
            top2--;
            array[top2] = element;
        }
        return true;
    }

    /**
     * 弹栈
     *
     * @param stackNum
     * @param element
     * @return
     */
    public boolean pop(int stackNum, Object element) {
        if (top1 == -1 || top2 == stackSize) {
            System.out.println("栈为空");
            return false;
        }

        if(stackNum == 1){
            array[top1] = null;
            top1--;
            return true;
        }else {

            array[top2] = null;
            top2++;
            return true;

        }


    }

    /**
     * 判断是否为空
     *
     * @param i
     * @return
     */
    public boolean isEmpty(int i) {
        if (i == 1) {
            if (top1 == -1) {
                return true;
            } else {
                return false;
            }
        } else {
            if (top2 == stackSize) {
                return true;
            } else {
                return false;
            }
        }
    }


    /**
     * 获取栈顶元素
     *
     * @param i
     * @return
     */
    public Object peek(int i) {
        if (i == 1) {
            if(top1 == -1){
                System.out.println("栈为空");
                return null;
            }
            return array[top1];
        } else {
            if(top2 == stackSize){
                System.out.println("栈为空");
                return null;
            }
            return array[top2];
        }
    }


    public static void main(String[] args) {
        BothStackShareMemory memory = new BothStackShareMemory();

//        memory.push(1,111);
        System.out.println(memory.peek(1));
    }
}


  • 7
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值