Stack Data Structure
Stack Data Structure
1. Introduction to Stacks
A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. The element
added most recently to the stack is the first one to be removed.
Stacks are analogous to a stack of plates in a cafeteria, where the last plate placed on top is the first
one removed.
2. Basic Terminology
• Push: The operation of adding an element to the stack.
• Pop: The operation of removing the top element from the stack.
• Peek (or Top): Fetching the value of the top element without removing it.
• Underflow: A condition where a pop operation is attempted on an empty stack.
• Overflow: A condition where a push operation is attempted on a full stack (in fixed-size
implementations).
3. Representation of Stacks
Stacks can be implemented in two main ways:
1. Using Arrays:
• Fixed size.
• Requires keeping track of the top index.
2. Using Linked Lists:
• Dynamic size.
• Each node contains the data and a pointer to the next node.
4. Operations on Stacks
Below are the primary operations performed on stacks:
5. Stack Applications
Stacks are widely used in various domains, including:
1. Expression Evaluation:
• Used in converting infix expressions to postfix or prefix.
• Evaluating postfix expressions.
2. Backtracking:
• For example, in solving maze problems, the last attempted path is retried.
3. Undo/Redo Operations:
• Used in text editors where the last action is undone or redone.
4. Call Stack:
• Manages function calls in programming.
5. Parenthesis Matching:
• Used to check for balanced parentheses in expressions.
Advantages:
• Simplicity.
• Efficient for fixed-size stacks.
Disadvantages:
• Fixed size may lead to stack overflow.
9. Complexity Analysis
Operation Time Complexity
Push O(1)
Pop O(1)
Peek O(1)