Titan Demon
Titan Demon

Reputation: 33

Passing Stack to a function

I am trying to solve a question on hackerrank.But I keep getting emptyStack exception every time.I think it might be because i am passing the stack to getMax function and it is changing the original stack.
I tried to write this in getMax hoping maybe it won't affect the final stack,but it didn't work.

Stack<Integer> s=st;

Can you point out and explain the mistake I am making.

ONE OF ERROR GIVING TEST CASE

Upvotes: 0

Views: 236

Answers (1)

zysaaa
zysaaa

Reputation: 1877

But I keep getting emptyStack exception every time.

Because when you execute stack.pop, the stack is already empty.

In your getMax method, Stack<Integer> s=st this operation does not copy the stack, which means that st and s refer to the same object, so your subsequent operations will affect the original stack.

Change Stack<Integer> s=st; to Stack<Integer> s= (Stack<Integer>) st.clone();.

Upvotes: 1

Related Questions