To find the first node in a linked list, you need to traverse through the list until you reach the head (or first) node. Here's an example implementation in Python:
main.py
classNode:def__init__(self, data): self.data = data
self.next = NoneclassLinkedList:def__init__(self): self.head = Nonedefadd_node(self, data): new_node = Node(data)
if self.head isNone:
self.head = new_node
return curr_node = self.head
while curr_node.nextisnotNone:
curr_node = curr_node.next curr_node.next = new_node
defget_first_node(self):return self.head
# initialize a linked listlinked_list = LinkedList()
linked_list.add_node(1)
linked_list.add_node(2)
linked_list.add_node(3)
# get the first nodefirst_node = linked_list.get_first_node()
print(first_node.data) # Output: 1