Complete the code to peek the top element of the stack.
int topElement = stack.[1]();The top() function 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 topElement = stack.top(); }
The empty() function checks if the stack has no elements.
Fix the error in the code to correctly peek the top element safely.
if (!stack.[1]()) { int topElement = stack.top(); }
We must check if the stack is not empty before accessing the top element. Using empty() returns true if empty, so condition should be negated.
Fill both blanks to create a function that returns the top element or -1 if stack is empty.
int peekTop(std::stack<int>& stack) {
if (stack.[1]()) {
return -1;
}
return stack.[2]();
}The function checks if the stack is empty using empty(). If empty, it returns -1. Otherwise, it returns the top element using top().
Fill all three blanks to create a safe peek function that prints the top or a message if empty.
void printTop(std::stack<int>& stack) {
if (stack.[1]()) {
std::cout << "Stack is empty" << std::endl;
} else {
int topElement = stack.[2]();
std::cout << "Top element: " << topElement << std::endl;
}
stack.[3]();
}The function first checks if the stack is empty using empty(). If not empty, it gets the top element with top(), prints it, and then removes it with pop().
