Operations on Stack: Definition, Examples, and Usage
stack are basic actions that manage data in a last-in, first-out (LIFO) order. The main operations include push to add an item, pop to remove the top item, peek to view the top item without removing it, and isEmpty to check if the stack has no items.How It Works
A stack is like a stack of plates where you can only add or remove the top plate. The push operation adds a new item on top of the stack, just like placing a new plate on the top. The pop operation removes the top item, similar to taking the top plate off the stack.
The peek operation lets you look at the top item without removing it, like checking the top plate without disturbing the stack. The isEmpty operation checks if there are any items left in the stack, helping you know if the stack is empty or not.
Example
This example shows how to use basic stack operations in Python using a list to simulate a stack.
stack = [] # Push operation stack.append(10) stack.append(20) stack.append(30) # Peek operation top_item = stack[-1] # Pop operation popped_item = stack.pop() # Check if stack is empty is_empty = len(stack) == 0 print(f"Top item after pushes: {top_item}") print(f"Item popped: {popped_item}") print(f"Stack after pop: {stack}") print(f"Is stack empty? {is_empty}")
When to Use
Stacks are useful when you need to reverse things or keep track of recent actions. For example, web browsers use stacks to manage the back button history, allowing you to go back to the last page you visited. Another use is in undo features in text editors, where the last change is undone first.
Stacks also help in programming tasks like parsing expressions, managing function calls, and backtracking algorithms where the last step must be undone before earlier steps.
Key Points
- Push: Add an item to the top of the stack.
- Pop: Remove the top item from the stack.
- Peek: View the top item without removing it.
- isEmpty: Check if the stack has no items.
- Stacks follow Last-In, First-Out (LIFO) order.