Stack Linked List in DSA Python

Program 1

#Stack Linked List

class Node:
    def __init__(self):
        self.data=None
        self.add=None

class StackLinkedList:
    def __init__(self):
          self.start=None

     #method for create list
    def createList(self):
       n=int(input("Enter an element"))
       self.start=Node()
       self.start.data=n
       self.start.add=None
       temp=self.start
       ch=input("Want to continue(Y/N)")
       while(ch=="Y"):
           n=int(input("Enter an element"))
           newnode=Node()
           newnode.data=n
           newnode.add=None
           temp.add=newnode
           temp=newnode
           ch=input("Want to continue(Y/N)")  
    
    # Push method of Stack linked list
    def pushData(self):
         if(self.start==None):
            print("Stack  Linked list is empty")
         else:
           n=int(input("Enter an element for push"))
           newnode=Node()
           newnode.data=n
           newnode.add=None
           temp=self.start
           while(temp.add!=None):
               temp=temp.add
           temp.add=newnode
      

    # Pop method of Stack linked list
    def popData(self):
        if(self.start==None):
              print("Statck Linked List is empty")
        else:
            temp=self.start
            while(temp.add!=None):
                  prev=temp
                  temp=temp.add
            print("Poped node is :",temp.data)                  
            prev.add=None
            temp=None
        

    # display method of Stack linked list
    def displayData(self):
        if(self.start==None):
            print("Stack  Linked list is empty")
        else:
            temp=self.start
            while(temp!=None):
                print(temp.data,end=" ")
                temp=temp.add
                

# Main Menu Application
mystack=StackLinkedList()
while(1):
    print("\n---------------Stack Linked List Menu-------------\n")
    print("1.Create")
    print("2.Push")
    print("3.Pop")
    print("4.Display")
    print("5.Exit")
    print("\n-------------------------------------------------------\n")
    choice=int(input("Enter your choice"))
    if(choice==1):
        mystack.createList()
    elif(choice==2):
        mystack.pushData()
    elif(choice==3):
        mystack.popData()        
    elif(choice==4):
        mystack.displayData()
    else:
        break    



    
    

 

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *