I'm new to data structures in python. i just started them past few weeks. i strucked with some code in python.
here is the code.
class Node:
def __init__(self,value):
self.data=value;
self.next=None;
class SinglyLinkedList:
def __init__(self):
self.head=None
self.tail=None
def display_List(head):
if head is not None:
print(head.data)
display_List(head.next)
def insert_in_beginning(self,value):
temp=Node(value)
temp.next=self.head;
self.head=temp;
def insert_at_end(self,value):
temp=Node(value)
if self.head is None:
self.head = temp;
else:
self.tail.next=temp;
self.tail=temp
def create_List(self):
n=int(input("enter no of nodes"));
if n==0:
return;
for i in range(n):
value = int(input("enter element to be inserted"));
self.insert_at_end(value)
list=SinglyLinkedList()
list.create_List()
option = int(input(" Enter your choice:"))
if option == 1:
list.display_List(list.head)
elif option ==2:
value= int(input("enter element to be inserted: "))
list.insert_in_beginning(value);
elif option ==3:
value= int(input("enter element to be inserted: "))
list.insert_at_end(value);
every thing is working fine except display_List function. I want to print the elements using recurssion way. I messed up some where.
but the code snippet is same and i changed the display_List to following function it is working good. i want to change it to recursive way.
def display_List(self):
if self.head is None:
print("List is empty")
return
else:
print("List is:",end=" ");
p=self.head
while p is not None:
print(p.data,end=" ")
p=p.next;
if option == 1:
list.display_List()
this function is working fine insteed of recursive. can someone please help me to correct this code.