Design a Stack With Increment Operation
July 27, 2020
Design a Stack With Increment Operation
class CustomStack {
Stack<Integer> stack;
Stack<Integer> temp = new Stack<>();
int count;
int maxSize;
public CustomStack(int maxSize) {
stack = new Stack<>();
this.maxSize = maxSize;
}
public void push(int x) {
if (count < maxSize) {
stack.push(x);
count++;
}
}
public int pop() {
if (stack.empty()) {
return -1;
}
count--;
return stack.pop();
}
public void increment(int k, int val) {
while (count > k) {
temp.push(stack.pop());
count--;
}
while (count > 0) {
temp.push(stack.pop() + val);
count--;
}
while (!temp.empty()) {
count++;
stack.push(temp.pop());
}
}
}