Check if Stack is Full
Check if Stack is Full
The operation to check if a stack is full involves determining if the stack has reached its maximum capacity. This is typically relevant for stacks implemented using arrays where a fixed size is predefined. A stack is considered full if the number of elements equals the maximum capacity of the stack.
Step-by-Step Process
To check if a stack is full, follow these steps:
- Initialize the Maximum Capacity: Define the maximum capacity for the stack.
- Track the Current Size: Keep a count of the current number of elements in the stack.
- Compare Size with Capacity: Compare the current size with the maximum capacity.
- Return Result: Return True if the current size equals the maximum capacity, indicating the stack is full. Otherwise, return False.
Pseudo Code
Function is_full(stack):
# Check if the current size equals the maximum capacity
If stack.size == stack.capacity:
Return True
# Otherwise, return False
Return False
Python Program to Check if Stack is Full
class Stack:
def __init__(self, capacity):
self.capacity = capacity
self.stack = []
self.size = 0
def push(self, data):
# Check if the stack is full
if self.is_full():
raise OverflowError("Stack is full")
# Add the new element to the stack
self.stack.append(data)
self.size += 1
def pop(self):
# Check if the stack is empty
if self.is_empty():
return None
# Remove the top element from the stack
self.size -= 1
return self.stack.pop()
def peek(self):
# Check if the stack is empty
if self.is_empty():
return None
# Return the top element of the stack
return self.stack[-1]
def is_empty(self):
# Check if the stack is empty
return self.size == 0
def is_full(self):
# Check if the current size equals the maximum capacity
return self.size == self.capacity
def traverse(self):
# Traverse and print the stack
for i in range(self.size - 1, -1, -1):
print(self.stack[i], end=" -> ")
print("None")
# Example usage:
stack = Stack(3)
print("Is stack full?", stack.is_full()) # Output: False
stack.push(1)
stack.push(2)
stack.push(3)
print("Stack after pushing 3 elements:")
stack.traverse() # Output: 3 -> 2 -> 1 -> None
print("Is stack full?", stack.is_full()) # Output: True
try:
stack.push(4)
except OverflowError as e:
print(e) # Output: Stack is full
stack.pop()
print("Stack after popping one element:")
stack.traverse() # Output: 2 -> 1 -> None
print("Is stack full?", stack.is_full()) # Output: False
This Python program defines a stack with a maximum capacity and methods for pushing elements onto the stack, popping elements from the stack, peeking at the top element of the stack, checking if the stack is empty, checking if the stack is full, and traversing the stack. The is_full method checks if the current size equals the maximum capacity and returns True if the stack is full, otherwise returns False.