Stack abstract data type concept
What you'll learn: Understand the "Last-In, First-Out" (LIFO) logic of a stack and how it manages data.
Imagine a literal stack of dinner plates in a cafeteria. When you finish washing a plate, you place it on the very top of the pile. When a hungry student comes by to grab a plate, they take the one from the top—the same one you just put down. You would never try to pull a plate out from the bottom of the stack; it would be messy, difficult, and likely result in broken ceramic.
In computer science, a Stack is an Abstract Data Type (ADT) that follows this exact logic. It is a linear collection of elements where you can only add or remove items from one end, called the "top."
The LIFO Principle
The defining rule of a stack is LIFO, which stands for Last-In, First-Out.
The last item you push onto the stack is the first item that must be removed. If you push the numbers 10, 20, and then 30 onto a stack, 30 is sitting at the top. To get back to the number 10, you must first remove 30, then remove 20.
Core Operations
To interact with a stack, we primarily use two functions:
- Push: Adds an element to the top of the stack.
- Pop: Removes the top element from the stack.
You might also use Peek (to look at the top item without removing it) or check if the stack is Empty.
A Conceptual Example in C
While we haven't built the underlying structure yet, here is how the logic of a stack looks in practice. Notice how we only ever interact with the "top."
#include <stdio.h>
// Imagine these functions are defined elsewhere to manage a stack
void push(int value);
int pop();
int main() {
// Adding items to the stack
push(10); // Stack: [10]
push(20); // Stack: [10, 20]
push(30); // Stack: [10, 20, 30] <- Top
// Removing items follows LIFO
int item = pop();
printf("Popped: %d\n", item); // Output: 30
item = pop();
printf("Popped: %d\n", item); // Output: 20
return 0;
}
This simple structure is incredibly powerful. Your computer uses a stack to keep track of function calls, and your web browser uses one to manage your "Back" button history.
Key takeaway
A stack is a LIFO (Last-In, First-Out) data structure where all additions and removals happen at the "top."