Exp 1
Exp 1
Experiment 1.1
Aim: Analyze if stack Isempty, Isfull and if elements are present then return top element in
stacks using templates and also perform push and pop operation in stack.
Procedure/Algorithm:
Step1: Create stack.
Step2: Check underflow and overflow condition.
Step3: Increment top to store element in stack.
Step4: Decrement top after removing element form stack.
Step5: Check is stack empty or not.
Sample Code:
class Stack:
def __init__(self, size):
self.data = [None] * size
self.top_index = -1
self.max_size = size
def is_empty(self):
return self.top_index == -1
def is_full(self):
return self.top_index == self.max_size - 1
def top(self):
if self.is_empty():
Name: Kartikeya UID: 21BCS6833
Course Name: DAA Lab Course Code: 21CSH-311
raise RuntimeError("Stack is empty.")
return self.data[self.top_index]
def pop(self):
if self.is_empty():
raise RuntimeError("Stack is empty.")
self.top_index -= 1
if __name__ == "__main__":
stack_size = int(input("Enter the size of the stack: "))
my_stack = Stack(stack_size)
my_stack.pop()
if my_stack.is_empty():
print("Stack is empty.")
elif my_stack.is_full():
print("Stack is full.")
Observations/Outcome :
Time Complexity:
The time complexity is O(n) where n is the number of elements pushed into the stack.