I have a simple implementation of LinkedList in python. How do I use recursion inside a method? I know how recursion works but how do I use self with recursion. It'd be nice if someone can fix my code but I am more interested in explanation so I can use it in different methods.
LinkedList code:
class Node:
def __init__(self, item, next):
self.item = item
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def add(self, item):
self.head = Node(item, self.head)
def remove(self):
if self.is_empty():
return None
else:
item = self.head.item
self.head = self.head.next
return item
def is_empty(self):
return self.head == None
My code is:
def count(self, ptr=self.head):
if ptr == None:
return '0'
else:
return 1 + self.count(ptr.next)
It gives me an error:
def count(self, ptr=self.head):
NameError: name 'self' is not defined
Any help is much appreciated.