题目
我的题解
解题时考虑到是否弹出后栈顶为空,所以采用ArrayList数据;然而,题目没有要求弹出后栈顶为空,所以使用数组更快更省地儿。
class CustomStack {
List stack;
int stackSize;
int index = 0;
public CustomStack(int maxSize) {
stackSize = maxSize;
stack = new ArrayList(stackSize);
}
public void push(int x) {
if (index < stackSize) {
stack.add(x);
index++;
}
}
public int pop() {
if (index > 0) {
index--;
return (int) stack.remove(index);
} else {
return -1;
}
}
public void increment(int k, int val) {
for (int i = 0; i < Math.min(k, index); i++) {
stack.set(i, (int) stack.get(i) + val);
}
}
}