Complete the code to peek the top element of the stack.
int topElement = stack.[1]();The peek() method returns the top element of the stack without removing it.
Complete the code to check if the stack is empty before peeking.
if (!stack.[1]()) { int top = stack.peek(); }
The empty() method returns true if the stack is empty, so we use !empty() to check if it has elements before peeking.
Fix the error in the code to correctly peek the top element safely.
if (!stack.isEmpty()) { int top = stack.[1](); }
Use peek() to get the top element without removing it. pop() removes the element, which is not desired here.
Fill both blanks to safely peek the top element or return -1 if empty.
int top = stack.[1]() ? -1 : stack.[2]();
Use isEmpty() to check if the stack is empty, then peek() to get the top element safely.
Fill both blanks to create a method that returns the top element or -1 if stack is empty.
public int peekTop(Stack<Integer> stack) {
return stack.[1]() ? -1 : stack.[2]();
}The method uses isEmpty() to check if the stack is empty and returns -1 if true; otherwise, it returns the top element using peek().
