How to Build a Linked List Node Class in Python
Create a Node class and a LinkedList class with insert, remove, and display methods to manage a singly linked list.
Python code
50 linesclass Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def remove(self, data):
if not self.head:
return False
if self.head.data == data:
self.head = self.head.next
return True
current = self.head
while current.next:
if current.next.data == data:
current.next = current.next.next
return True
current = current.next
return False
def display(self):
result = []
current = self.head
while current:
result.append(current.data)
current = current.next
return result
if __name__ == "__main__":
ll = LinkedList()
ll.insert(10)
ll.insert(20)
ll.insert(30)
print("After insert:", ll.display())
print("Remove 20:", ll.remove(20))
print("After remove:", ll.display())
print("Remove 99:", ll.remove(99))
Output
After insert: [10, 20, 30]
Remove 20: True
After remove: [10, 30]
Remove 99: False
How it works
Each Node holds data and a reference to the next node. insert appends a new node at the tail by traversing to the last node. remove finds the first matching node and links the previous node to the next, effectively deleting it. The head pointer marks the start, ensuring updates when the head is removed. Display walks the chain and collects values. This classic OOP pattern mirrors how lists work under the hood in languages like C.
Common mistakes
- Forgetting to update the head when removing the first node
- Not handling an empty list before remove
- Traversing past the end when current becomes None
- Comparing data with `is` instead of `==`
Variations
- Use a sentinel node to simplify boundary cases
- Implement insert at head for O(1) prepend operations
- Make the class generic with type hints
Real-world use cases
- Implementing internal data structures like LRU caches where fast head/tail operations matter
- Managing undo/redo functionality in editors with a linked list of states
- Building adjacency lists for graph traversal algorithms in memory-efficient ways
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.