Stack using Linked List in DSA Python

Program 1

# Stack Linked list
import os
class Node:
    def __init__(self):
        self.data=None
        self.add=None
        
class StackLinkedList:
    def __init__(self):
        self.start=None
        self.count=0

    def create(self):
        n=int(input("Enter First element: "))    
        self.start=Node()
        self.start.data=n
        self.start.add=None
        self.temp=self.start
        self.count=self.count+1
        ch=input("Wan to continue(Y/y): ")
        while(ch=='y' or ch=='Y'):
            self.count=self.count+1
            n=int(input("Enter next element: "))    
            newnode=Node()
            newnode.data=n   # assign data to new node
            newnode.add=None # assign address to new node
            self.temp.add=newnode 
            self.temp=self.temp.add
            ch=input("Wan to continue(Y/y): ")

    def push(self):
     if(self.start==None):
          print("Stack is empty")
     else:
          self.count=self.count+1
          n=int(input("Enter an element: "))
          newnode=Node()
          newnode.data=n
          newnode.add=None
           
          top=self.start
          while(top.add!=None):
              top=top.add

          top.add=newnode

    def pop(self):  
        try:         
            if(self.start==None):
                 print("Stack is empty")
            else:     
                self.count=self.count-1  
                top=self.start
                while(top.add!=None):
                    prev=top
                    top=top.add

                print("Poped element is: ",top.data)                    
                prev.add=None
                top=None
        except:
           self.start=None
           
    def display(self):
        if(self.start==None):
          print("Stack is empty")
        else:     
            temp=self.start
            while(temp!=None):
                print(temp.data)
                temp=temp.add
                  
          
          
#Main
os.system('cls')
st=StackLinkedList()
while(1):
    print("------------------------Stack Linked List------------------------")
    print("1. Create \n 2. Push \n 3. Pop \n 4. Display \n 5. Exit")
    print("------------------------------------------------------------------")
    choice=int(input("Enter your choice: "))
    if(choice==1):
        st.create()
    elif(choice==2):
        st.push()
    elif(choice==3):
        st.pop()        
    elif(choice==4):
        st.display()    
    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 *