0
Hey i am new to java stack ,,please help me in finding mistake in this problem.
#Java # stack
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
+ 3
Thank you for helping me😍