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++];
}
}
}
网友评论