Implementation of Stack Using Array
Stack: A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. The element added last is the one to be removed first.
Stacks are widely used in various applications such as expression evaluation, backtracking, and function call management.
How to Implement a Stack Using an Array?
- Define an array to store stack elements.
- Maintain a variable top to track the index of the topmost element in the stack.
- Initialize top to -1 to indicate an empty stack.
- Implement the following operations:
- Push: Add an element to the top of the stack and increment top.
- Pop: Remove the top element from the stack and decrement top.
- Peek: Retrieve the top element without removing it.
- IsEmpty: Check if the stack is empty by verifying if top is -1.
- IsFull: Check if the stack is full by comparing top with the maximum size of the array.
Advantages:
- Simple and easy to implement.
- Efficient for small and fixed-size stacks.
Disadvantages:
- Fixed size: The maximum size of the stack must be defined in advance.
- Wastage of memory if the stack is not fully utilized.
Time Complexity:
- Push: O(1)
- Pop: O(1)
- Peek: O(1)