Stacks follow the Last-In-First-Out (LIFO) principle. Elements are added and removed from the same end, called the top. Think of it like a stack of plates - you can only add or remove plates from the top.
Elements are added and removed from the top only
Last element added is the first to be removed
Constant time push, pop, and top operations
Easy to understand and implement operations
Used in recursion, parsing, and function calls
Add an element to the top of the stack
Remove and return the top element
View the top element without removing it
Check if the stack has no elements
Managing function calls and local variables
Converting infix to postfix expressions
Implementing undo functionality in applications
Solving maze problems and puzzles
Operation | Time Complexity | Description |
---|---|---|
Push | O(1) | Add element to top |
Pop | O(1) | Remove element from top |
Top/Peek | O(1) | Access top element |
IsEmpty | O(1) | Check if stack is empty |
Space Complexity: O(n) where n is the number of elements