The core property of a Stack data structure is that it allows adding and removing elements only from one endpoint i.e, there is only one opening through which we can add or remove elements. To make it intuitive and easy to understand, we generally visualize stack as a pile of elements stacked on top of each other. Adding or removing elements will be done from the top end of pile.
Similar behavior can be achieved using an array by adding or removing elements after the last element present in the array. You can visualize this as a horizontal stack. Each time a new element has to be pushed to the stack, it can be added after the last element present in the array. Similarly when the top element has to be popped off the stack, the last element in the array can be returned.
In this way, each operation โpush, pop, top and is_emptyโ can be achieved in constant time O(1).
Note: We can also replicate behavior of Stack by adding and removing elements from the beginning of array. But this is not efficient as all the elements after the top element have to be relocated every time a new element is added/removed from the beginning of stack.
Below is the code to implement stack using an array:
class StackUsingArray:
def __init__(self, size):
self.size = size
# Initialize an array which can hold 'size' elements
self.array = [None] * size
# Initialize top index to -1 (Indicates empty stack)
self.top_idx = -1
def push(self, item):
# Check if there's space in the array
if self.top_idx < self.size - 1:
# Increment the top element and add item
self.top_idx += 1
self.array[self.top_idx] = item
return True
else:
print("Stack Overflow!")
return False
def pop(self):
if not self.is_empty():
item = self.array[self.top_idx]
self.array[self.top_idx] = None # Clearing the value
self.top_idx -= 1
return item
else:
print("Stack Underflow!")
return None
def top(self):
if not self.is_empty():
return self.array[self.top_idx]
else:
return None
def is_empty(self):
if self.top_idx == -1:
return true;
else:
return false;
Here is how the code works:
Constructor or __init__:- In this method, we initialize the stack by creating an empty array of desired size.
top_idxis set to -1 to indicate an empty stack.
pushmethod:- The
pushmethod adds an item to the top of stack. - The last element in the array is considered as the top of stack.
- So when pushing an item, we increment
top_idxand add new element at the incremented index. - This makes sure that the new element is added after the last existing element in the array.
- It also checks if there’s space available (
top_idx<self.size - 1) before pushing the new element.
- The
popmethod:- The
popmethod removes the top item from the stack. - The last element in the array is considered as the top of stack.
- So the element at
top_idxposition is returned top_idxis also decremented to indicate that the next last element will be the top element.
- The
topmethod:- The
topmethod retrieves the top item from the stack without removing it. It simply looks at the item at thetop_idxposition in the array (array[self.top_idx]) and returns that item.
- The
is_emptymethod:- The
is_emptymethod checks if the stack is empty by examining the value oftop_idx. - If
top_idxis -1, it means there are no items in the stack, indicating that the stack is empty.
- The