A simple, lightweight implementation of a singly linked list data structure in Python, built using a nested Node class.
This project provides a clean implementation of a singly linked list — a fundamental data structure where each element (node) holds a value and a reference (pointer) to the next node in the sequence. It supports basic operations such as adding elements, removing elements, and checking whether the list is empty.
The implementation uses two classes:
Represents a single node in the list.
| Attribute | Description |
|---|---|
element |
The value stored in the node |
next |
Pointer to the next node (None if last) |
Manages the chain of nodes.
| Attribute | Description |
|---|---|
head |
Points to the first node in the list |
length |
Tracks the number of elements in the list |
- Python 3.x
python Linked_List.pyNo external dependencies are required.
from Linked_List import LinkedList
# Create a new linked list
my_list = LinkedList()
# Check if empty
my_list.is_empty() # True
# Add elements
my_list.add(1)
my_list.add(2)
my_list.add(3)
# Remove an element
my_list.remove(2)
# Check length
print(my_list.length) # 2Returns True if the list has no elements, False otherwise.
my_list.is_empty() # TrueAppends a new element to the end of the linked list. Traverses the list from the head to find the last node and links the new node to it.
my_list.add(10)
my_list.add(20)Time Complexity: O(n) — traverses to the end of the list.
Removes the first occurrence of the specified element from the list. Handles three cases:
- Element is not found — no changes are made.
- Element is the head node — head pointer is updated.
- Element is in the middle or end — the previous node's
nextpointer skips over it.
my_list.remove(10)Time Complexity: O(n) — traverses the list to find the element.
Running the script as-is produces the following output:
True
False
2
1
- No indexing — elements cannot be accessed by position.
- No duplicate handling —
remove()only deletes the first match. - Linear performance — both
add()andremove()are O(n); a tail pointer could optimizeadd()to O(1).