java中两栈共享空间的代码_两栈共享空间(java实现)

如果我们有两个相同类型的栈,我们为他们各自开辟了数组空间,极有可能第一个栈已经满了,再进栈就溢出了,而另一个栈还有很多存储空间空闲。这时,我们可以充分利用顺序栈的单向延伸的特性,使用一个数组来存储两个栈,让一个栈的栈底为数组的始端,另一个栈的栈底为数组的末端,每个栈从各自的端点向中间延伸。

如下图所示:

1b1f4991aec0282100aae5ce938a5633.png

其中,top1和top2分别为栈1和栈2的栈顶指针,size为整个数组空间的大小,栈1的底固定在下标为0的一端,栈2的底固定在下标为size-1的一端。

实现代码:

package com.dhy.seqstack;

/**

* 两栈共享空间

* @author Administrator

*

*/

public class BothStack {

private Object[] element; //存放元素的数组

private int stackSize; // 栈大小

private int top1; //栈1的栈顶指针

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

/**

* 初始化栈

* @param size

*/

public BothStack(int size){

element = new Object[size];

stackSize = size;

top1 = -1;

top2 = stackSize;

}

/**

* 压栈

* @param i 第几个栈

* @param o 入栈元素

* @return

*/

public boolean push(int i , Object o){

if(top1 == top2 - 1)

throw new RuntimeException("栈满!");

else if(i == 1){

top1++;

element[top1] = o;

}else if(i == 2){

top2--;

element[top2] = o;

}else

throw new RuntimeException("输入错误!");

return true;

}

/**

* 出栈

* @param i

* @return

*/

@SuppressWarnings("unchecked")

public T pop(int i){

if(i == 1){

if(top1 == -1)

throw new RuntimeException("栈1为空");

return (T)element[top1--];

} else if(i == 2){

if(top2 == stackSize)

throw new RuntimeException("栈2为空");

return (T)element[top2++];

} else

throw new RuntimeException("输入错误!");

}

/**

* 获取栈顶元素

* @param i

* @return

*/

@SuppressWarnings("unchecked")

public T get(int i){

if(i == 1){

if(top1 == -1)

throw new RuntimeException("栈1为空");

return (T)element[top1];

} else if(i == 2){

if(top2 == stackSize)

throw new RuntimeException("栈2为空");

return (T)element[top2];

} else

throw new RuntimeException("输入错误!");

}

/**

* 判断栈是否为空

* @param i

* @return

*/

public boolean isEmpty(int i){

if(i == 1){

if(top1 == -1)

return true;

else

return false;

} else if(i == 2){

if(top2 == stackSize)

return true;

else

return false;

} else

throw new RuntimeException("输入错误!");

}

/**

* 遍历

*/

@SuppressWarnings("unchecked")

@Override

public String toString(){

String str1 = "栈1:[";

String str2 = "栈2:[";

for(int i=top1;i>=0;i--){

if(i == 0)

str1 = str1 + (T)element[i];

else

str1 = str1 + (T)element[i] + ",";

}

str1 += "]";

for(int i=top2;i

if(i == stackSize-1)

str2 = str2 + (T)element[i];

else

str2 = str2 + (T)element[i] + ",";

}

str2 += "]";

return str1 + "\n\r" + str2;

}

}

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值