find the first node in a linked list in python

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
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None
    
    def add_node(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
            return
        curr_node = self.head
        while curr_node.next is not None:
            curr_node = curr_node.next
        curr_node.next = new_node
    
    def get_first_node(self):
        return self.head
    
# initialize a linked list
linked_list = LinkedList()
linked_list.add_node(1)
linked_list.add_node(2)
linked_list.add_node(3)

# get the first node
first_node = linked_list.get_first_node()
print(first_node.data) # Output: 1
742 chars
32 lines

gistlibby LogSnag