I have started implementing linked list in python , I was able to create a traverse method and how to insert in the beginning of list method but while implementing this method of insertion of a node after a specific node , I have observed a code online that uses prev_node
as one of the parameters including data
, my question here is , all this time I thought only a single value parameters can be passed as param but not something that could be bundled with other attributes , for instance , data
here is single value parameter but when it comes to prev_node
it has prev_node.pointer
in it and since it's a parameter we are passing , not sure how does this have a property of node which is pointer
in this scenario? could someone please help on how is this working ? Here is the code
class Node():
def __init__(self,data):
self.data=data
self.pointer=None
class LinkedList():
def __init__(self):
self.head=None
def add_beg(self,data):
""" add data in the beginning """
new_node=Node(data)
new_node.pointer=self.head
self.head=new_node
def traverse(self):
if self.head is None:
print('no value found ')
return
else:
current=self.head
while current is not None:
print(current.data,'')
current=current.pointer
def add_after(self,prev_node,data):
""" add data after the specific node """
new_node=Node(data)
new_node.pointer=prev_node.pointer #Here is the part I do not understand
prev_node.pointer=new_node