Reputation: 1666
I am implementing a minstack algorithm and across something strange, Maybe I am missing either 'Some Stack concept' or 'Some Java concept' here. I am making using of two stacks(st and st2) to perform my minstack operations. Below is my pop method which fails at if condition:
Method 1 - FAILS:
public void pop() {
if(st.pop() == st2.peek())
st2.pop();
}
Below is the Pop method which works fine when I store the st.pop() results in a variable 'a':
Method 2 - PASSES:
public void pop() {
int a = st.pop();
if(a == st2.peek())
st2.pop();
}
Please assume that there are integer elements in both the stacks and the value from st.pop()
is equal to st2.peek()
. I would like the understand the difference as to why the st.pop()
would not work in if state of method 1 and works in method 2 after storing results of st.pop()
into a temporary variable a
Upvotes: 1
Views: 60
Reputation: 770
If I understand the question correct, st.pop()
doesn't work in the first method because the type of elements in st are never explicitly stated (ie. st could be initialized like Stack st = new Stack();
).
As a result, any object (doesn't have to be an int) could be pushed onto the stack, so when the stack is popped, it's unclear what data type is returned, which causes the if statement to fail.
In the second method, the popped item is explicitly defined as an int in the variable a, so when the comparison is made with a, the if statement works as expected.
Upvotes: 1