1.兩棧共享空間
public class TwoStackShare {
private static final int MAX_SIZE = 10;
private int top1 = -1;
private int top2 = MAX_SIZE;
private Object[] data;
public void push(int stackNumber, Object element) {
if (top1 + 1 == top2) {
throw new RuntimeException("棧滿");
}
if (stackNumber == 1) {
data[++top1] = element;
} else {
data[--top2] = element;
}
}
public Object pop(int stackNumber) {
if (stackNumber == 1) {
if (top1 == -1) {
throw new RuntimeException("棧1空");
}
return data[top1--];
} else {
if (top2 == MAX_SIZE) {
throw new RuntimeException("棧2空");
}
return data[top2++];
}
}
}