Site icon DataFlair

Create, Display and Reverse Display in Doubly Linked List in DSA Python

Program 1

# Implementation of Doubly Linked List

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

class DoubleLinkedList:        
      def __init__(self):
           self.start=None
           self.count=0

      # Create method of list
      def createList(self):
           n=int(input("Enter an element"))
           self.start=Node()
           self.start.ladd=None
           self.start.data=n
           self.start.radd=None
           temp=self.start
           self.count=self.count+1
           choice=input("Want to continue")
           while(choice=="Y" or choice=="y"):
                n=int(input("Enter next element"))
                newnode=Node()
                newnode.ladd=None
                newnode.data=n
                newnode.radd=None
                temp.radd=newnode
                newnode.ladd=temp
                temp=temp.radd
                self.count=self.count+1
                choice=input("Want to continue")

         # Display method of list
      def displayList(self):
           if(self.start==None):
                print("List not found")
           else:
                temp=self.start
                while(temp!=None):
                     print(temp.data,end=" ")
                     temp=temp.radd
                print("\nTotal Node is : ",self.count)                     

  
        #Method for reverse display          
      def reverseDisplay(self):
           if(self.start==None):
                print("List not found")
           else:
                temp=self.start
                while(temp.radd!=None):
                     temp=temp.radd

                while(temp!=None): 
                     print(temp.data,end=" ")
                     temp=temp.ladd
                print("\nTotal Node is : ",self.count)                      

#Main Menu
mylist=DoubleLinkedList()
while(1):
    print("\n-------------------------Doubly Linked List-----------------------")                        
    print("1. Create")
    print("2. Display")
    print("3. Reverse Display")
    print("4. Insert First")
    print("5. Insert Middle")
    print("6. Insert Last")
    print("7. Delete First")
    print("8. Delete Middle")
    print("9. Delete Last")
    print("10.Serching")
    print("11. Exit")
    print("-------------------------------------------------------------------")
    choice=int(input("Enter your choice"))
    if(choice==1):
         mylist.createList()
    elif(choice==2):
         mylist.displayList()
    elif(choice==3):
         mylist.reverseDisplay()       
    else:
         break

 

Exit mobile version