# The same algorithm, but one get wrong result

• public class MinStack {

``````private Stack<Integer> stack = new Stack<Integer>();
private Stack<Integer> minstack = new Stack<Integer>();

public void push(int x){
stack.push(x);
if(minstack.empty()) minstack.push(x);
else{
if(x<=minstack.peek()) minstack.push(x);
}
}

public void pop(){
if(!stack.empty()){
int x = stack.pop();
if(x == minstack.peek())
minstack.pop();

}
}

public int top(){
return stack.peek();
}

public int getMin(){
if(!minstack.empty())
return minstack.peek();
return Integer.MAX_VALUE;
}
``````

}
Another code for pop():
public void pop(){
if(!stack.empty()){
if(stack.peek() == minstack.peek())
minstack.pop();
stack.pop();
}
}
Here I get the wrong result
if we push(512),push(-1024),push(-1024),push(512)
then at the second time of pop(), it should also pop the -1024 from minstack, but it doesn't.
Why???

• You know what, I met the same thing and figure out why it happens.

The problem lies in if(stack.peek() == minstack.peek()).

Because both stack and minstack are Integer typed, the peek() for both is a Integer, not int. If you want to compare two Integer, need to use equals(), or cast both to int.

Solution1:

if(stack.peek().equals(minstack.peek()))

Solution2:

if((int)stack.peek() == (int)minstack.peek())

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.