[ADS-FINAL-PREP] 3. Stack
A Stack is a data structure operating on the LIFO (Last In, First Out) principle, meaning the last element added to the stack is the first one to be removed. Imagine a stack of plates: you can only pick up the plate at the top.
Core Stack Operations
- push(x) — Adds element
xto the top of the stack. - pop() — Removes and returns the top element from the stack.
- peek() / top() — Views the top element without removing it.
- isEmpty() — Checks whether the stack is empty.
- size() — Returns the total number of elements in the stack.
Use Cases
Stacks are widely used in algorithms and software engineering:
- Reverse Order Evaluation: Performing computations in Reverse Polish Notation (RPN).
- Recursion: Managing function calls via the call stack.
- Undo Functionality: Implementing the "Undo" action in text editors and games.
- Parentheses Balancing: Checking the validity of bracket expressions.
- Graph Traversal: Implementing Depth-First Search (DFS).
Advantages of a Stack
- Simplicity: Straightforward implementation.
- High Performance: All basic operations execute in O(1) time complexity.
Disadvantages of a Stack
- Restricted Access: You can only access the topmost element.
- Size Limitations: Can be fixed in size if implemented using a static array.
If you noticed a mistake or copyright issues, please contact: lebroskiofficial@proton.me