java中两栈共享空间的代码_数据结构(七)两栈共享空间

packagebigjun.iplab.doubleStack;public class DoubleStack implementsDoubleStackINF{private final static int MAXSIZE = 20;private int[] stackElem;private int top1; //将top1设置为指向栈1栈顶元素的存储位置即数组下标

private int top2; //将top2设置为指向栈2栈顶元素的存储位置即数组下标

publicDoubleStack() {

top1= -1;

top2=MAXSIZE;

stackElem= new int[MAXSIZE];

}public booleanisStackEmpty() {if (top1 == -1 && top2 ==MAXSIZE)return true;else

return false;

}public voidstackClear() {

top1= -1;

top2=MAXSIZE;

}public intstackLength() {return (top1 + 1) + (MAXSIZE -top2);

}public int getTop1Elem() throwsException{if (top1 == -1)throw new Exception("栈1为空,无法获取栈顶元素");returnstackElem[top1];

}public int getTop2Elem() throwsException{if (top2 ==MAXSIZE)throw new Exception("栈2为空,无法获取栈顶元素");returnstackElem[top2];

}public void stackPush(int stackNumber, int e) throwsException {if (top1 + 1 ==top2)throw new Exception("栈为满,无法在栈顶插入元素e");if (stackNumber == 1) {

top1++;

stackElem[top1]=e;

}else if (stackNumber == 2) {

top2--;

stackElem[top2]=e;

}

}public void stackPop(int stackNumber) throwsException {if (stackNumber == 1) {if (top1 == -1)throw new Exception("栈1为空,无法获取栈顶元素");

top1--;

}else if (stackNumber == 2) {if (top2 ==MAXSIZE)throw new Exception("栈2为空,无法获取栈顶元素");

top2++;

}

}public voidstackTraverse() {

System.out.print("此时,栈中的元素为: ");int i = 0;while (i <=top1) {

System.out.print(stackElem[i++] + " ");

}

i=top2;while (i

System.out.print(stackElem[i++] + " ");

}

System.out.println();

}public static void main(String[] args) throwsException {

DoubleStack seqStack= newDoubleStack();for (int j = 1; j <= 5; j++)

seqStack.stackPush(1,j);for (int i = MAXSIZE; i >= MAXSIZE -2 ; i--) {

seqStack.stackPush(2, i);

}

seqStack.stackTraverse();

System.out.println("栈的长度为: " +seqStack.stackLength());

seqStack.stackPop(2);

seqStack.stackTraverse();

System.out.println("栈1的栈顶元素为: " +seqStack.getTop1Elem());

System.out.println("栈2的栈顶元素为: " +seqStack.getTop2Elem());

System.out.println("栈的长度为: " +seqStack.stackLength());for (int i = 6; i <= MAXSIZE-2; i++) {

seqStack.stackPush(1,i);

}

seqStack.stackTraverse();

System.out.println("栈1的栈顶元素为: " +seqStack.getTop1Elem());

System.out.println("栈2的栈顶元素为: " +seqStack.getTop2Elem());

System.out.println("栈顶元素为: " +seqStack.getTop2Elem());

System.out.println("栈的长度为: " +seqStack.stackLength());

System.out.println("栈是否为空: " +seqStack.isStackEmpty());

seqStack.stackClear();

System.out.println("栈是否为空: " +seqStack.isStackEmpty());

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值