Site icon DataFlair

Stack using Collection in DSA Python

Program 1

#Implementation of stack using collections
from collections import deque
class MyStack:
    def __init__(self):
        self.stack=deque()

    def push(self,item):        
          self.stack.append(item)
          print("Pushed : ",item)

    def pop(self):          
         if(len(self.stack)==0):
              print("Stack is empty , can not pop element")
         else:
                  print("Poped element is: ",self.stack.pop())

    def display(self):
           if(len(self.stack)==0):
              print("Stack is empty , can not display elements")
           else:
             
            for element in reversed(self.stack):
                 print(element)

# Main
S=MyStack()
while(1):
    print("------------------Stack Menu--------------------")
    print("1. Push \n 2. Pop \n 3. Display \n 4.Exit")
    print("---------------------------------------------------")
    choice=int(input("Enter your choice: "))
    if(choice==1):
         n=int(input("Enter an element for push: "))
         S.push(n)
    elif(choice==2):
         S.pop()         
    elif(choice==3):
         S.display()
    else:
         break

 

Exit mobile version