Topic: Describe how you could use a single array to implement three stacks.
// 情况1:fixed division. 数组等分成三份。
If it is ok with simply allocating a fixed amount of space for each stack, we can divide the array in three equal parts. This may mean though that one stack runs out of space, while the others are nearly empty. 如果有额外信息,也可以Stack 1 have more space than stack 2...
// 情况2:flexible division. 一个栈从头开始,一个从尾开始,一个从中间/三分之一开始,记录1,2的top, 3的top和end,有数据进来,就整体移3.
1)Define two stacks beginning at the end of the array, growing in opposite directions. The third stack start in the middle of the array. 2) Redefine the push op, when going to overwrite other stack, shift the whole middle stack before pushing. 3) store the top for the first two, store the beginning and the end of the last stack.
public class C3 {
static int stackSize=100;
static int[]buffer=new int[stackSize*3];
// 3 stack pointers to track the top element
static int[] pointer={-1,-1,-1};
static void push(int stackNum, int value) throws Exception{
//有可能容量不够,所以要throws exception
if(pointer[stackNum]+1>=stackSize){
throw new Exception("Out of space");
}
pointer[stackNum]++;
buffer[TopOfStack(stackNum)]=value;
}
static int pop(int stackNum) throws Exception{
if(pointer[stackNum]==-1){
throw new Exception("Popoing an empty stack");
}
int value=buffer[TopOfStack(stackNum)];
buffer[TopOfStack(stackNum)]=0;//pop之后栈顶元素置零
pointer[stackNum]--;
return value;
}
static int peek(int stackNum){
return buffer[TopOfStack(stackNum)];
}
static int TopOfStack(int stackNum){
return stackNum*stackSize+pointer[stackNum];
}
public static void main(String[] args) throws Exception{
push(2, 4);
System.out.println("Peek 2: " + peek(2));
push(0, 3);
push(0, 7);
push(0, 5);
System.out.println("Peek 0: " + peek(0));
pop(0);
System.out.println("Peek 0: " + peek(0));
pop(0);
System.out.println("Peek 0: " + peek(0));
}
}
// 结果
Peek 2: 4
Peek 0: 5
Peek 0: 7
Peek 0: 3