private Stack<Integer> st; private Stack<Integer> stMax; /** initialize your data structure here. */ publicMaxStack(){ st = new Stack<>(); stMax = new Stack<>(); } publicvoidpush(int x){ st.push(x); if (stMax.isEmpty()) stMax.push(x); else{ if (x >= stMax.peek()) stMax.push(x); else stMax.push(stMax.peek()); } } publicintpop(){ stMax.pop(); return st.pop(); } publicinttop(){ return st.peek(); } publicintpeekMax(){ return stMax.peek(); } publicintpopMax(){ Stack<Integer> temp = new Stack<>(); int max = stMax.peek(); while(st.peek() != max){ temp.push(st.pop()); stMax.pop(); } st.pop(); stMax.pop(); while(!temp.isEmpty()){ this.push(temp.pop()); } return max; } }
/** * Your MaxStack object will be instantiated and called as such: * MaxStack obj = new MaxStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.peekMax(); * int param_5 = obj.popMax(); */