Stack: Data Entered Last Comes Out First
A stack is a data structure where the last element added is the first to be removed, which is known as Last In First Out (LIFO)
.
In simple terms, it works like stacking books where you take the book from the top first.
A stack allows data to be added or removed in a limited fashion and is used in various program functionalities such as browser history, undo functions, and more.
Basic Operations of a Stack
A stack consists of the following main operations:
-
Push
: Adds a new element to the top of the stack. -
Pop
: Removes the most recently added element from the stack and returns that element. -
Peek (or Top)
: Returns the top element of the stack without removing it. -
IsEmpty
: Checks if the stack is empty.
How Can a Stack Be Implemented?
In Python, a simple stack can be implemented using a list.
# Initialize stack
stack = []
# Push elements
stack.append(1)
stack.append(2)
stack.append(3)
# Peek at the top element
print(stack[-1])
# Output: 3
# Pop the top element
print(stack.pop())
# Output: 3
print(stack.pop())
# Output: 2
# Check if the stack is empty
print(len(stack) == 0)
# Output: False
You can find a more detailed stack implementation using Class
in the code editor on the right.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.