//一个数组固定分割实现三个栈
public class StackByArray {
//栈大小
int stackSize = 100;
//三个栈的栈顶指针
int[] stactTopOfStack = {-1,-1,-1};
//存放数据的数组
int[] theArray = new int[stackSize*3];
//入栈方法
void push(int stackNum,int x){
if (stactTopOfStack[stackNum]+1>stackSize){
return;
}
//栈顶指针自增,然后更新栈顶元素
stactTopOfStack[stackNum]++;
theArray[topOfStack(stackNum)]=x;
}
//出栈方法
int pop(int stackNum) throws Exception{
if (stactTopOfStack[stackNum]==-1){
throw new Exception("栈是空的,无法出栈");
}
//获取栈顶的元素,并将栈顶位置清零,同时指针自减
int value = theArray[topOfStack(stackNum)];
theArray[topOfStack(stackNum)] = 0;
stactTopOfStack[stackNum]--;
return value;
}
int top(int stackNum) throws Exception{
if (stactTopOfStack[stackNum]==-1){
throw new Exception("栈是空的,无法获得栈顶元素");
}
return theArray[topOfStack(stackNum)];
}
/*返回索引为stackNum栈的栈顶元素,在数组中的索引*/
int topOfStack(int stackNum){
return stackSize * stackNum + stactTopOfStack[stackNum];
}
public static void main(String[] args) {
StackByArray stack = new StackByArray();
//向第一个栈插入数据
stack.push(0, 1);
stack.push(0, 2);
//向第二个栈插入数据
stack.push(1, 3);
stack.push(1, 4);
//向第三个栈插入数据
stack.push(2, 5);
stack.push(2, 6);
try {
System.out.println(stack.pop(0));
System.out.println(stack.top(0));
System.out.println(stack.pop(0));
System.out.println(stack.pop(0));
} catch (Exception e) {
e.printStackTrace();
}
}
}
数据结构(二):一个数组固定分割实现三个栈
最新推荐文章于 2024-08-18 21:36:31 发布