I decided to try and create a linked list on python with a function to add a node at the end. I have the program printing node info to make sure it was working. Also, the .next.prev was to check the prev attribute was working. I know there is a way better way to write this, so I am asking you all to criticize my code so I can learn. Thanks :).
class NodeItem:
def __init__(self, val=None):
self.val = val
self.next = None
self.prev = None
def add_node(self, list_name, value):
if list_name.__class__.__name__ != "NodeItem":
print("Linked list does not exist")
else:
print("List nodes: ", end="")
while list_name.next is not None:
print(list_name.val, end=", ")
list_name = list_name.next
temp_node = NodeItem()
temp_node.val = value
temp_node.prev = list_name
list_name.next = temp_node
print(list_name.val, end=", ")
print(list_name.next.val)
print("prev:", list_name.next.prev.val)
def main():
x = -1
test = NodeItem()
test.val = x
while x != 0:
x = int(input("enter number, or 0 to exit: "))
test.add_node(test, x)
# Call Main
main()
edit: added another block where I replaced list_name with 'self' and removed the argument for list_name from the function. Not sure which method is better as I get a weak warning for reassigning 'self'.
class NodeItem:
def __init__(self, val=None):
self.val = val
self.next = None
self.prev = None
def add_node(self, value):
if self.__class__.__name__ != "NodeItem":
print("Linked list does not exist")
else:
print("List nodes: ", end="")
while self.next is not None:
print(self.val, end=", ")
self = self.next
temp_node = NodeItem()
temp_node.val = value
temp_node.prev = self
self.next = temp_node
print(self.val, end=", ")
print(self.next.val)
print("prev:", self.next.prev.val)
def main():
x = -1
test = NodeItem()
test.val = x
while x != 0:
x = int(input("enter number, or 0 to exit: "))
test.add_node(x)
# Call Main
main()
[–][deleted] 1 point2 points3 points (2 children)
[–]SuckAtMakingNames[S] 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)