0

Hey i am new to java stack ,,please help me in finding mistake in this problem.

#Java # stack

1st May 2023, 7:14 PM
baibhav kumar
baibhav kumar - avatar
2 Respostas
+ 5
it will throw an exception at runtime because you are trying to call the peek() method on an empty stack st. You need to add a condition to check if the stack is empty before calling the peek() method. Rectify loop: for (int i = 0; i < arr.length; i++) { //First here check stack is empty or not while (!st.isEmpty() && arr[i] > st.peek()) { System.out.println(arr[i] + ">" + st.peek()); st.pop(); } // we can simply use if to add elements when stack is empty or has first value smaller value than a[i] if (st.isEmpty() || arr[i] <= st.peek()) { st.push(arr[i]); } } Your code: https://code.sololearn.com/c8T26ME5XGGx/?ref=app
1st May 2023, 7:26 PM
Just Some Random Guy
Just Some Random Guy - avatar
+ 3
Thank you for helping me😍
2nd May 2023, 5:45 AM
baibhav kumar
baibhav kumar - avatar