← Back to all snippets
PYTHON

Building a Simple Singly Linked List in Python

Understand the fundamentals of a singly linked list in Python, a dynamic data structure where elements are linked via pointers, useful for custom data management.

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 not self.head:
            self.head = new_node
            return
        last_node = self.head
        while last_node.next:
            last_node = last_node.next
        last_node.next = new_node

    def display(self):
        current = self.head
        elements = []
        while current:
            elements.append(str(current.data))
            current = current.next
        print(" -> ".join(elements))

    def find(self, key):
        current = self.head
        while current:
            if current.data == key:
                return current
            current = current.next
        return None

# Example Usage
my_list = LinkedList()
my_list.append(10)
my_list.append(20)
my_list.append(30)
print("Linked List:")
my_list.display()

found_node = my_list.find(20)
if found_node:
    print(f"Found node with data: {found_node.data}")
else:
    print("Node not found.")

my_list.append(40)
my_list.display()
How it works: This snippet defines a `Node` class and a `LinkedList` class to implement a basic singly linked list. Each `Node` holds `data` and a reference (`next`) to the subsequent node. The `LinkedList` class manages the `head` node. Methods like `append` add new nodes to the end, `display` prints the list elements, and `find` searches for a specific data value, illustrating how elements are chained together.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs