| 9 | import java.util.Stack; |
| 10 | |
| 11 | class MaxStack { |
| 12 | private Stack<Integer> stack; |
| 13 | private Stack<Integer> maxStack; |
| 14 | |
| 15 | public MaxStack() { |
| 16 | stack = new Stack<>(); |
| 17 | maxStack = new Stack<>(); |
| 18 | } |
| 19 | |
| 20 | public void push(int x) { |
| 21 | int max = maxStack.isEmpty() ? x : Math.max(maxStack.peek(), x); |
| 22 | stack.push(x); |
| 23 | maxStack.push(max); |
| 24 | } |
| 25 | |
| 26 | public int pop() { |
| 27 | maxStack.pop(); |
| 28 | return stack.pop(); |
| 29 | } |
| 30 | |
| 31 | public int top() { |
| 32 | return stack.peek(); |
| 33 | } |
| 34 | |
| 35 | public int peekMax() { |
| 36 | return maxStack.peek(); |
| 37 | } |
| 38 | |
| 39 | public int popMax() { |
| 40 | int max = peekMax(); |
| 41 | Stack<Integer> buffer = new Stack<>(); |
| 42 | while (top() != max) { |
| 43 | buffer.push(pop()); |
| 44 | } |
| 45 | pop(); // Remove the max element |
| 46 | while (!buffer.isEmpty()) { |
| 47 | push(buffer.pop()); |
| 48 | } |
| 49 | return max; |
| 50 | } |
| 51 | } |
nothing calls this directly
no outgoing calls
no test coverage detected