Stack in Python

Stack is a data structure that follows LIFO (Last In First Out) operation in a list of elements. Push, Pop, Traverse are some of the common operations in a stack.

Write a program in Python to implement the concept of push, pop and traverse in a statically allocated stack.

#Implement the concept of push, pop and traverse
#in a statically allocated stack.
def push(stack, element, size):
    if len(stack) == size:
        print("STACK OVERFLOW")
    else:
        stack.append(element)
        top = len(stack) - 1

def pop(stack):
    if stack == []:
        return "STACK UNDERFLOW"
    element = stack.pop()
    if len(stack) == 0:
        top = None
    else:
        top = len(stack) - 1
    return element

def traverse(stack):
    if stack == []:
        print("STACK UNDERFLOW")
    else:
        for i in range(0, len(stack)):
            print(stack[i], end = "\t")
        print();

my_stack = []
top = None
size = int(input("ENTER STACK SIZE: "))
while True:
    print("1. PUSH")
    print("2. POP")
    print("3. TRAVERSE")
    choice = int(input("ENTER YOUR CHOICE: "))
    if choice == 1:
        element = int(input("ENTER THE ELEMENT: "))
        push(my_stack, element, size)
    elif choice == 2:
        element = pop(my_stack)
        if element == "STACK UNDERFLOW":
            print(element)
        else:
            print(str(element) + " POPPED!")
    elif choice == 3:
        traverse(my_stack)
    else:
        print("BYE!")
        break

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.