Recall & Review
beginner
What does the 'peek' operation do in a stack?
The 'peek' operation returns the top element of the stack without removing it, allowing you to see the current top value.
Click to reveal answer
beginner
In a stack implemented using an array, which index usually represents the top element?
The top element is usually at the index represented by the 'top' variable, which points to the last inserted element.
Click to reveal answer
intermediate
What should the 'peek' function do if the stack is empty?
If the stack is empty, the 'peek' function should handle it gracefully, often by returning a special value or indicating an error, since there is no top element to show.
Click to reveal answer
beginner
Show the basic C code snippet to peek the top element of a stack implemented with an array and a 'top' index.
int peek(int stack[], int top) {
if (top == -1) {
// Stack is empty
return -1; // or some error code
}
return stack[top];
}
Click to reveal answer
beginner
Why is it important that 'peek' does not remove the top element from the stack?
Because 'peek' is meant only to view the top element without changing the stack's state, so other operations can still use the stack as expected.
Click to reveal answer
What does the 'peek' operation return in a stack?
✗ Incorrect
Peek returns the top element without removing it from the stack.
If the stack is empty, what should the peek function do?
✗ Incorrect
Peek should handle empty stack by returning an error or special value since no top element exists.
In a stack implemented with an array, what does the 'top' variable represent?
✗ Incorrect
'top' points to the index of the current top element in the stack array.
Which of these is true about the peek operation?
✗ Incorrect
Peek returns the top element but does not remove it from the stack.
What value is commonly used to indicate an empty stack in C implementations?
✗ Incorrect
top = -1 usually means the stack is empty in array-based stack implementations.
Explain how the peek operation works in a stack implemented with an array.
Think about how you find the last added item without changing the stack.
You got /4 concepts.
Describe why peek is useful and how it differs from pop in stack operations.
Consider what happens to the stack after each operation.
You got /4 concepts.
