Implementing the Peek function
What you'll learn: How to view the top element of a stack without removing it.
In our journey with Stacks (Last-In, First-Out), we have already learned how to push (add) and pop (remove) items. However, there are many times when you just want to see what is currently sitting at the very top of the stack without disturbing it. This is where the Peek function comes in.
The "Top of the Pringles Can" Analogy
Imagine a can of Pringles chips. A Pringles can is a classic stack.
- If you Push, you drop a chip in.
- If you Pop, you take the top chip out to eat it.
- If you Peek, you simply look into the can to see what flavor the top chip is.
When you Peek, the chip stays in the can. The "size" of your stack does not change, and the data remains exactly where it was.
Coding the Peek logic
To implement peek, we need to access the array at the index indicated by our top pointer. However, we must first ensure the stack isn't empty. Trying to "peek" at an empty stack is like looking into an empty Pringles can—there is nothing to see, and in C, trying to access an invalid index could crash your program.
Here is how we implement it using a basic array-based stack:
#include <stdio.h>
#include <stdbool.h>
#define MAX 5
int stack[MAX];
int top = -1; // -1 means the stack is empty
// Peek function returns the top element
int peek() {
// 1. Check if the stack is empty
if (top == -1) {
printf("Error: Stack is empty, nothing to peek.\n");
return -1;
}
// 2. Return the value at the current top index
// Note: We do NOT decrement the top variable!
return stack[top];
}
int main() {
stack[++top] = 10; // Pushing 10
stack[++top] = 20; // Pushing 20
int topValue = peek();
printf("The top element is: %d\n", topValue);
// The stack still contains 10 and 20.
return 0;
}
Why use Peek?
You might wonder why we don't just pop the value and then push it back. While that works, it is inefficient. peek is a "read-only" operation. It is essential in algorithms like expression parsing, where you need to check if the top of the stack is a specific character (like a parenthesis) before deciding what to do with the next piece of data.
Key takeaway
The peek function returns the value of the top element without modifying the stack's pointer or removing any data.