Skip to content

Instantly share code, notes, and snippets.

@Edmartt
Last active December 27, 2023 20:20
Show Gist options
  • Save Edmartt/89cdd35673d605eec9a5578b8b5b1089 to your computer and use it in GitHub Desktop.
Save Edmartt/89cdd35673d605eec9a5578b8b5b1089 to your computer and use it in GitHub Desktop.
Linked Lists in Python OOP version
class Node:
def __init__(self, data: int, next=None):
self.data = data
self.next = next
class LinkedList:
def add_elements(self, init_node: Node, data: int):
new_node = Node(data=data, next=None) # new node with the data and next reference
if init_node[0] == None:
init_node[0] = new_node #now we can simulate modifying the reference as a pointer to the list. This adds the new node to the list and method ends.
else:
current_node = init_node[0] #when the node sent as argument is not None
while current_node.next is not None: # We access here when the next attribute is not None
current_node = current_node.next #If we access this loop we'll be setting the next node reference of the following node
current_node.next = new_node # when we jump the loop because it has the next attribute with None value, we say that the next atributte is the new node object
def show_elements(self, node: Node):
current = node[0]
while current:
print("{} -> ".format(current.data), end="")
current = current.next
my_list = LinkedList()
node = [None] # This always has just 1 element, because the other elements are nested inside the firs element. i.e element1 -> element2 -> element3 etc
my_list.add_elements(node, 7)
current = node[0]
print(current.next) #first next reference is None, because we only have 1 node and not next reference for now
my_list.add_elements(node, 14)
current = node[0]
print(current.next) # after adding the second node, the reference is not None, this element will be the first next reference
my_list.add_elements(node, 18)
current = node[0].next # we need to go inside the node[0] and access to it's next reference which is the previous added node
print(current.next)
my_list.show_elements(node)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment