Stack: Piling Up Like Plates
A stack
is a data structure that piles up data like plates on a table.
When you remove plates from the pile, you take the topmost plate first. Similarly, in a stack, the most recently added data is the first to be removed.
This follows the LIFO(Last In, First Out)
principle, meaning "the last one in is the first one out."
How is a stack used?
-
Web browser's back button: Browsers store the pages you visit in a stack. Each time you click the back button, it returns you to the
last visited page
in order. -
Undo function in text editors: Text editors save the text you input in a stack. Each time you undo, it removes the
last input text
in order.
Main Operations of a Stack
There are a few basic operations used with stacks:
-
push: This operation
adds
new data to the top of the stack. -
pop: This operation
removes and returns
the data at the top of the stack. -
peek: This operation
checks
the data at the top of the stack without removing it. -
is_empty: This operation checks whether the stack is
empty
.
Implementing a Stack in Python
In Python, you can easily implement a stack using a list.
You can use the list's append()
method to add data and the pop()
method to remove data, thereby implementing the basic functionalities of a stack.
class Stack:
# Initialize the stack
def __init__(self):
self.stack = []
# push operation: Add data to the stack
def push(self, item):
self.stack.append(item)
print(f"Push: {item} has been added to the stack.")
# pop operation: Remove data from the stack
def pop(self):
if not self.is_empty():
item = self.stack.pop()
print(f"Pop: {item} has been removed from the stack.")
return item
else:
print("Pop: The stack is empty.")
return None
# peek operation: Check the top value of the stack
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
print("Peek: The stack is empty.")
return None
def is_empty(self):
return len(self.stack) == 0
# Example of using the stack
my_stack = Stack()
my_stack.push(1) # Push: 1 has been added to the stack
my_stack.push(2) # Push: 2 has been added to the stack
print(f"Peek: The current top value of the stack is {my_stack.peek()}.")
my_stack.pop() # Pop: 2 has been removed from the stack
my_stack.pop() # Pop: 1 has been removed from the stack
my_stack.pop() # The stack is empty, cannot remove item
In Summary
-
A stack follows the
LIFO(Last In, First Out)
structure. -
The main operations include push(add), pop(remove), peek(check), and is_empty(check if empty).
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.