find the smallest node in a linked list in python

To find the smallest node in a linked list in Python, you can traverse the linked list and keep track of the smallest node encountered so far. Here's a sample implementation:

main.py
class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None

def find_smallest_node(head):
    if head is None:
        # Empty linked list
        return None

    smallest_node = head
    current_node = head.next

    while current_node is not None:
        if current_node.data < smallest_node.data:
            smallest_node = current_node
        current_node = current_node.next

    return smallest_node
448 chars
20 lines

In this implementation, we start by checking if the linked list is empty (i.e. head is None). If it is, we simply return None.

Otherwise, we initialize smallest_node to be the first node in the linked list, and current_node to be the second node. We then traverse the linked list using a while loop until we reach the end of the list (i.e. current_node is None).

During each iteration, we compare current_node's data to smallest_node's data. If current_node's data is smaller, we update smallest_node. We then move on to the next node in the linked list by setting current_node to its next node.

Once we've reached the end of the linked list, we return smallest_node.

You can use this function as follows:

main.py
# Create a linked list
head = Node(3)
node2 = Node(5)
node3 = Node(1)
node4 = Node(4)
head.next = node2
node2.next = node3
node3.next = node4

# Find the smallest node
smallest_node = find_smallest_node(head)
print(smallest_node.data)  # Output: 1
248 chars
13 lines

gistlibby LogSnag