This code should create a node but I have a problem with it I tried to fix it but I couldn`t
I want to know why there is a problem at in the Linked_List (Next_Node)
that is what show in the error "(Cannot assign member "next_node" for type "node" Expression of type "node | None" cannot be assigned to member "next_node" of class "node" Type "node | None" cannot be assigned to type "None" Type cannot be assigned to type "None")"
class node :
data = None
next_node = None
def __init__(self , data) :
self.data = data
def __repr__(self) :
return "<node data: %s>" % self.data
class linked_list :
def __init__(self ):
self.head = None
def add (self , data):
new_node = node(data)
new_node.next_node = self.head
self.head = new_node
def __repr__ (self):
nodes =[]
current = self.head
while current :
if current is self.head:
nodes.append ("[:head %s ]" % current.data)
elif current.next.node is None :
nodes.append ("[tail: %s ]" % current.data)
else :
nodes.append ("[:%s ]" % current.data)
current = current.next_node
return "->".join(nodes)
CodePudding user response:
There are several problems with current attempt:
- The Node class as pointed by John Gordon is wrongly constructed. The
data
andnext_node
should be in__init__
method. - The
add
method is not adding new node in correct position. - The
__repr__
is not looping through all the nodes in the linked list because of wrong indentation.
Updated code:
class node:
def __init__(self, data):
self.data = data
self.next_node = None
def __repr__(self):
return "<node data: %s>" % self.data
class linked_list:
def __init__(self):
self.head = None
def is_empty(self):
return self.head == None
def size(self):
current = self.head
count = 0
while current:
count = 1
current = current.next_node
return count
def add(self, data):
new_node = node(data)
if self.head == None:
self.head = new_node
else:
current = self.head
while current.next_node != None:
current = current.next_node
current.next_node = new_node
def __repr__(self):
nodes = []
current = self.head
while current:
if current is self.head:
nodes.append("[:head %s ]" % current.data)
elif current.next_node is None:
nodes.append("[tail: %s ]" % current.data)
else:
nodes.append("[:%s ]" % current.data)
current = current.next_node
return "->".join(nodes)
l = linked_list()
l.add(1)
l.add(2)
l.add(3)
print(l)
Output:
[:head 1 ]->[:2 ]->[tail: 3 ]
CodePudding user response:
class node :
data = None
next_node = None
def __init__(self , data):
self.data = data
I think the problem is because of the node
class definition.
The way you've defined the next_node
variable, it is a direct attribute of the class, so it is shared among all instances of the class.
I think you intended that attribute to be inside the __init__
method, so that each instance would have its own separate copy of that variable:
class node :
def __init__(self , data) :
self.data = data
self.next_node = None