Bachelor of Science in Computer Science
Course ContentStacks
Habari ya leo, future tech leaders of Kenya!
Welcome back to Data Structures and Algorithms. Today, we are tackling a concept that is as simple as it is powerful, and you actually use it every single day without even thinking about it. We're talking about Stacks!
Ever wondered how the "Back" button on your web browser knows exactly which page to return to? Or how the "Undo" function in your document editor can reverse your last action? The secret behind this magic is the humble Stack. Let's peel back the layers!
What is a Stack? The Chapati Analogy!
Imagine you are at home, and your mum has just finished making a delicious pile of hot chapatis for supper. She places them one on top of the other on a plate. Now, when you come to serve yourself, which chapati do you take first? The one at the very top, right? You don't dig to the bottom to get the first one she made. That would just be messy!
> **Image Suggestion:** [A vibrant, warm, top-down photograph of a stack of freshly made Kenyan chapatis on a ceramic plate. One hand is gently lifting the topmost chapati off the stack. The style should be realistic and inviting, like a food blog photo.]A Stack is a linear data structure that follows a specific order in which operations are performed. That order is LIFO (Last-In, First-Out). Just like our chapatis: the last one placed on the pile is the first one to be taken off.
ASCII Art: The Chapati Stack
[ Chapati 4 (Last-In) ] <-- You take this one first (First-Out)
[ Chapati 3 ]
[ Chapati 2 ]
[ Chapati 1 (First-In)]
-------------------------
(Plate)
The Main Operations: The Language of Stacks
Stacks have a few core operations that we must know. They are very straightforward.
- Push: This means adding a new element to the top of the stack. (Placing another hot chapati on the pile).
- Pop: This means removing the element from the top of the stack. (Taking the top chapati to eat).
- Peek (or Top): This means looking at the top element without removing it. (Checking if the top chapati is burnt without taking it off the pile).
- IsEmpty: This checks if the stack is empty. (Checking if all the chapatis are finished!).
Let's see it in action!
Imagine we have an empty stack (an empty plate). Let's follow the operations step-by-step.
1. Initial State: Stack is empty.
[ ]
---------
2. Push(10): We add the number 10.
[ 10 ] <-- Top
---------
3. Push(20): We add the number 20.
[ 20 ] <-- Top
[ 10 ]
---------
4. Push(30): We add the number 30.
[ 30 ] <-- Top
[ 20 ]
[ 10 ]
---------
5. Pop(): We remove the top element (30). The returned value is 30.
[ 20 ] <-- Top is now 20
[ 10 ]
---------
6. Peek(): We look at the top element. It's 20. The stack doesn't change.
[ 20 ] <-- Top
[ 10 ]
---------
Real-World Applications: Stacks are Everywhere!
Sawa, so this is more than just about chapatis. Stacks are a fundamental concept in computer science.
M-Pesa Menu Navigation: Think about navigating the M-Pesa STK menu on your phone. You go from 'Lipa na M-Pesa' -> 'Pay Bill' -> 'Enter business no.'. To go back, you press '0'. Each menu is pushed onto a stack. Pressing '0' is like a 'pop' operation, taking you back to the previous menu.> **Image Suggestion:** [A split-screen illustration. On the left, a simplified diagram of a stack with labels like "Main Menu", "Lipa na M-Pesa", "Pay Bill". On the right, a stylized smartphone screen showing the M-Pesa "Pay Bill" interface. An arrow points from the phone screen to the "Pay Bill" item on the stack.]
Other common examples include:
- Browser History: The "Back" button in Chrome or Firefox pops the last visited URL from a stack.
- Undo/Redo Functionality: When you type in a Word document, each action (typing, deleting, formatting) is pushed onto a stack. Pressing Ctrl+Z (Undo) pops the last action.
- Function Call Stack: When your program calls functions, the computer uses a stack to remember where to return to when a function finishes. This is a bit more advanced, but it's a critical use of stacks!
Let's Get Practical: A Simple Stack in Python
In Python, you can easily implement a stack using a simple list. The list's append() method works perfectly as push, and its pop() method does exactly what a stack's pop should do!
# Let's create our chapati stack using a Python list
chapati_stack = []
# Push operations (Mum is cooking!)
chapati_stack.append("Chapati 1")
chapati_stack.append("Chapati 2")
chapati_stack.append("Chapati 3")
print(f"Stack after cooking: {chapati_stack}")
# Peek operation (Checking the top one)
# We can look at the last element with index [-1]
top_chapati = chapati_stack[-1]
print(f"Let's peek at the top one: {top_chapati}")
# Pop operation (Time to eat!)
eaten_chapati = chapati_stack.pop()
print(f"We just ate the: {eaten_chapati}")
print(f"Stack after eating one: {chapati_stack}")
# Pop again
eaten_chapati = chapati_stack.pop()
print(f"We just ate another one: {eaten_chapati}")
print(f"Stack now: {chapati_stack}")
Time for a Little Math: Performance
You might be wondering, how fast are these operations? The beauty of a stack is its efficiency. Because we only ever work with the top element, all the main operations are incredibly fast.
Time Complexity of Stack Operations
------------------------------------
Push: O(1) - Constant Time
Pop: O(1) - Constant Time
Peek: O(1) - Constant Time
------------------------------------
O(1) means the operation takes the same amount of time regardless of how many items are in the stack. Whether you have 10 chapatis or 10,000, adding one more to the top takes the same, single step!
Conclusion
And there you have it! The Stack. A simple, elegant data structure based on the LIFO principle. From managing your web history to serving chapatis, it’s a powerful tool in a programmer's toolkit. Understanding it is a key step to becoming a great software developer.
Next time you hit that 'Undo' button, give a little nod to the stack working hard behind the scenes. Asanteni sana for your attention. Let's get ready for our next topic!
Pro Tip
Take your own short notes while going through the topics.