I take two stacks s1
and s2
, initialize them with some values, and eventually, both have -1024
as there top
.
Now, if I compare peeks of both in an if
condition, the results are coming wrong. For example:
if (s1.peek() == s2.peek()) --> returns false
Even when both peeks have -1024
as the values.
BUT
If I take the values in different variables, and then compare, that works just fine. For example:
int first = s1.peek();
int second = s2.peek();
if (first == second) --> returns true
I checked same with other values (eg 10). Direct peek comparison works fine in that case.
Am I doing something wrong by comparing peeks directly or is this related to values being compared somehow?
Below is the minimal coded example (I was doing this just as a practice to implement min stack problem):
public class MinStack {
public static void main(String[] args) {
MinStack minStack = new MinStack();
minStack.push(512);
minStack.push(-1024);
minStack.push(-1024);
minStack.push(512);
minStack.pop();
System.out.print(minStack.getMin());
minStack.pop();
System.out.print(minStack.getMin());
minStack.pop();
System.out.print(minStack.getMin());
}
Stack<Integer> originalStack;
Stack<Integer> minStack;
/** initialize your data structure here. */
public MinStack() {
originalStack = new Stack<>();
minStack = new Stack<>();
}
public void push(int x) {
originalStack.push(x);
if(minStack.isEmpty() || minStack.peek() >= x)
minStack.push(x);
}
public void pop() {
if(originalStack.peek() == minStack.peek())
minStack.pop();
originalStack.pop();
}
public int top() {
return originalStack.peek();
}
public int getMin() {
return minStack.peek();
}
}