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.
The program is running perfectly fine for some test cases.(0,2,27)
Question Link : https://www.hackerrank.com/challenges/maximum-element/copy-from/243724938
My solution:
import java.util.*; class Solution { static void getMax(Stack<Integer> st) { Stack<Integer> s=st; int max=s.peek(); s.pop(); while(!s.empty()) { if(s.peek()>max) max=s.peek(); s.pop(); } System.out.println(max); } public static void main(String args[]) { Stack<Integer> s=new Stack<Integer>(); Scanner sc=new Scanner(System.in); int n=sc.nextInt(); while(n-->0) { int c=sc.nextInt(); if(c==1) s.push(sc.nextInt()); else if(c==2) s.pop(); else getMax(s); } } }
CodePudding user response:
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();
.