I have the following code, and I'm trying to implement insert function(without any OOP technique). The output coming was 1. Which basically means that the variable root was not passed as a reference. Is there any specific way, I can do that?? Secondly, I can implement it using a separate linked list class, in that case my root node will be unique for every linked list class object, and I won't have this problem of root being mishandled.
Can you please suggest, how can I implement it in the following way:-
class Node:
def __init__(self, data):
self.data = data
self.next = None
def insert(root, data):
temp = root
root = Node(data)
root.next = temp
root = Node(1)
insert(root, 2)
print(root.data)
whereas, then I implemented the following code, obviously it is working, but I want the above code to work:-
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.root = None
def insert(self, data):
temp = self.root
self.root = Node(data)
self.root.next = temp
ll = LinkedList()
ll.insert(5)
ll.insert(6)
print(ll.root.data)
Assigning to
root
will not modify the object thatroot
points to, but you can still modify the properties ofroot
: