If you’re brushing up on data structures in Python, linked lists are a great place to start. Unlike arrays (Python’s built-in lists), linked lists are made up of nodes that point to each other — making them flexible for insertions and deletions.
This post walks you through implementing a basic singly linked list from scratch in Python.
What Is a Linked List?
A linked list is a sequence of nodes where:
- Each node contains some data.
- Each node points to the next node.
Think of it as a treasure hunt where each clue leads to the next.
Step 1: Define a Node
class Node:
def __init__(self, data):
self.data = data # Value stored in the node
self.next = None # Pointer to the next node
Step 2: Create the LinkedList Class
class LinkedList:
def __init__(self):
self.head = None # Start with an empty list
def append(self, data):
# Insert a new node at the end.
new_node = Node(data)
if not self.head:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
def prepend(self, data):
# Insert a new node at the beginning.
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def delete(self, data):
# Delete the first node with the given data.
if not self.head:
return
if self.head.data == data:
self.head = self.head.next
return
current = self.head
while current.next:
if current.next.data == data:
current.next = current.next.next
return
current = current.next
def print_list(self):
# Print all nodes in the list.
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
Example Usage
ll = LinkedList()
ll.append(10)
ll.append(20)
ll.append(30)
ll.print_list() # 10 -> 20 -> 30 -> None
ll.prepend(5)
ll.print_list() # 5 -> 10 -> 20 -> 30 -> None
ll.delete(20)
ll.print_list() # 5 -> 10 -> 30 -> None
Why Use Linked Lists?
Operation | Array (list) | Linked List |
---|---|---|
Random Access | O(1) | O(n) |
Insertion/Deletion | O(n) | O(1)* |
*O(1) if you already have a reference to the node
Use linked lists when:
- You care about insertions/deletions more than fast lookups.
- You don’t know how many items you’ll need upfront.
Level Up 🧠
Want to go further? Try these challenges:
- Reverse a Linked List (LeetCode #206)
- Detect Cycle in a Linked List (LeetCode #141)
- Merge Two Sorted Lists (LeetCode #21)
- Remove N-th Node From End (LeetCode #19)
This is part of my “Data Structures in Python” series. Next up: Stacks & Queues.