DataStructures with Python
About Lesson

# STACK

def isEmpty(stk):
    if stk==[]:
        return True
    else:
        return False

def push(stk,item):
    stk.append(item)
    top=len(stk)-1

def pop(stk):
    if isEmpty(stk):
        return “Under Flow”
    else:
        item=stk.pop()
        if len(stk)==0:
            top=None
        else:
            top=len(stk)-1
        return item

def peek(stk):
    if isEmpty(stk):
        return “Under Flow”
    else:
        top=len(stk)-1
        return stk[top]

def disp(stk):
    if isEmpty(stk):
        print(“Stack is Empty”)
    else:
        top=len(stk)-1
        print(stk[top],”<–top”)
        for a in range(top-1,-1,-1):
            print(stk[a])

#main program
stk=[]
top=None

while True:
    print(“STACK MENU”)
    print(“1. Push”)
    print(“2. Pop”)
    print(“3. Peek”)
    print(“4. Print”)
    print(“5. Exit”)
    ch=int(input(“Enter your choice as 1,2,3,4 or 5: “))

    if(ch==1):
        item=int(input(“Enter your data:”))
        push(stk,item)
    elif ch==2:
        item=pop(stk)
        if item==”Under Flow”:
            print(“Under Flow, Stack is Empty”)
        else:
            print(“Poped item is:”,item)
    elif ch==3:
        item=peek(stk)
        if item == “Under Flow”:
            print(“Under Flow, Stack is Empty”)
        else:
            print(“Top most item is:”, item)

    elif ch==4:
        disp(stk)    elif ch==5:
          break
    else:
        print(“Invalid Input”)

You cannot copy content of this page