find the last node in a linked list in python

To find the last node in a linked list, you need to traverse the list until you reach the tail node, which is the node that has a None value as its next pointer. Here's an 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 append(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 find_last(self):
        if self.head is None:
            return None
        curr_node = self.head
        while curr_node.next is not None:
            curr_node = curr_node.next
        return curr_node
662 chars
27 lines

In this implementation, Node represents a node in the linked list with some data and a next pointer to the next node in the list. LinkedList represents the linked list itself, with a head pointer to the first node in the list.

The append method adds a new node to the end of the list by traversing the list until it finds the last node, then setting the next pointer of that node to the new node.

The find_last method traverses the list in the same way to find the last node and returns it. If the list is empty (head is None), it returns None instead.

gistlibby LogSnag