0
0
Data-structures-theoryConceptBeginner · 3 min read

Stack Data Structure: Definition, Usage, and Example

A stack is a data structure that stores items in a last-in, first-out (LIFO) order, meaning the last item added is the first one removed. It works like a stack of plates where you add or remove only from the top.
⚙️

How It Works

A stack works like a pile of plates: you can only add a new plate on top and remove the top plate first. This means the last item you put in is the first one you take out, which is called Last-In, First-Out (LIFO).

Imagine stacking books on a table. You place one book on top of another. When you want to take a book, you pick the top one first. You cannot take a book from the middle without removing the ones above it.

This simple rule makes stacks useful for tasks where you need to reverse order or keep track of recent actions.

💻

Example

This example shows a stack using a list in Python. We add items with push and remove them with pop, following the LIFO rule.

python
class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if not self.is_empty():
            return self.items.pop()
        return None

    def is_empty(self):
        return len(self.items) == 0

stack = Stack()
stack.push('apple')
stack.push('banana')
stack.push('cherry')
print(stack.pop())  # cherry
print(stack.pop())  # banana
print(stack.pop())  # apple
Output
cherry banana apple
🎯

When to Use

Stacks are useful when you need to reverse things or remember recent actions. For example:

  • Undo features in text editors, where the last change is undone first.
  • Backtracking algorithms, like solving mazes or puzzles.
  • Parsing expressions in calculators or compilers.
  • Managing function calls in programming languages (call stack).

Whenever you need to process items in reverse order of arrival, a stack is a good choice.

Key Points

  • A stack follows Last-In, First-Out (LIFO) order.
  • Items are added and removed only from the top.
  • Common operations are push (add) and pop (remove).
  • Used in undo systems, expression evaluation, and function calls.

Key Takeaways

A stack stores data in last-in, first-out (LIFO) order.
You can only add or remove items from the top of the stack.
Stacks are ideal for undo features, parsing, and managing function calls.
The main operations are push (add) and pop (remove).