一个数组实现两个栈
基本思路:
1.定义两个栈顶top1=-1,top2=maxsize
2.栈满,当top1与top2相差1时栈满
package 例题;
//一个数组实现两个栈
public class TwoStack {
private int[] arr;
private int maxSize;
//定义栈顶
private int top1;
private int top2;
public TwoStack(int maxSize) {
if (maxSize<2){
System.out.println("数组大小不能小于2");
return;
}
this.maxSize = maxSize;
arr=new int[maxSize];
top1=-1;
top2=maxSize;
}
//入栈
public void push(int stackid,int value){
if (top1+1==top2){
System.out.println("已满");
return;
}
if (stackid==1){
top1++;
arr[top1]=value;
}else if (stackid==2){
top2--;
arr[top2]=value;
}else {
System.out.println("没有这个栈");
return;
}
}
//出栈
public int pop(int stackid) throws Exception{
if (stackid==1){
if (top1==-1){
throw new Exception("栈1为空");
}
return arr[top1--];
}else if (stackid==2){
if (top2==maxSize){
throw new Exception("栈2为空");
}
return arr[top2++];
}else {
throw new Exception("没有这个栈");
}
}
public void list(int stackid){
if (stackid==1){
for (int i =0; i <=top1 ; i++) {
System.out.println("stack["+i+"]="+arr[i]);
}
}
else if (stackid==2){
for (int i =maxSize-1; i >=top2 ; i--) {
System.out.println("stack["+i+"]="+arr[i]);
}
}else {
System.out.println("没有这个栈");
}
}
}