A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. It can be implemented using an array by treating the end of the array as the top of the stack.
A stack can be implemented using an array where we maintain:
An integer array to store elements.
A variable capacity to represent the maximum size of the stack.
A variable top to track the index of the top element. Initially, top = -1 to indicate an empty stack.
Adds an item to the stack. If the stack is full, then it is said to be an Overflow condition.
Before pushing the element to the stack, we check if the stack is full.
If the stack is full (top == capacity-1) , then Stack Overflows and we cannot insert the element to the stack.
Otherwise, we increment the value of top by 1 (top = top + 1) and the new value is inserted at top position .
The elements can be pushed into the stack till we reach the capacity of the stack.
Time Complexity: O(1) Auxiliary Space: O(1)
Pop Operation:
Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.
Before popping the element from the stack, we check if the stack is empty .
If the stack is empty (top == -1), then Stack Underflows and we cannot remove any element from the stack.
Otherwise, we store the value at top, decrement the value of top by 1 (top = top β 1) and return the stored top value.
Time Complexity: O(1) Auxiliary Space: O(1)
Top or Peek Operation in Stack:
Returns the top element of the stack.
Before returning the top element from the stack, we check if the stack is empty.
If the stack is empty (top == -1), we simply print βStack is emptyβ.
Otherwise, we return the element stored at index = top.
Popped: 4
Top element: 3
Is stack empty: No
Is stack full: No
Stack Implementation using Dynamic Array
When using a fixed-size array, the stack has a maximum capacity that cannot grow beyond its initial size. To overcome this limitation, we can use dynamic arrays. Dynamic arrays automatically resize themselves as elements are added or removed, which makes the stack more flexible.
In C++, we can use vector.
In Java, we can use ArrayList.
In Python, we can use list.
In C#, we can use List.
In JavaScript, we can use Array.
Output
Popped: 4
Top element: 3
Is stack empty: No
Current size: 3