Back to: Python Data Structure and Algorithims
Welcome to Linked Lists
Let’s begin our journey into data structures with one of the most fundamental concepts — the Linked List.
Before we understand what a linked list is, let’s first recall something familiar — a Python list.
🧠 Understanding a Normal Python List
In Python, when we create a list like this:
This list has indexes and is stored in a contiguous block of memory.
That means all its elements are placed right next to each other in memory, something like this:
| Index | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| Value | 10 | 20 | 30 | 40 |
💡 Because the elements are stored together, we can quickly access any element using its index:
This is called O(1) time access, meaning it takes constant time to retrieve any element.
🔗 Moving from Lists to Linked Lists
Now, let’s transform our Python list into a Linked List step by step.
🟣 Step 1: Remove Indexes
A linked list doesn’t use indexes.
Instead, each element (called a node) knows only about the next node in the sequence.
So, instead of:
We’ll have something like:
Each arrow (→) represents a link or a pointer from one node to the next.
⚙️ Step 2: Nodes and Pointers
In a linked list:
-
Each element is called a Node.
-
Each Node has:
-
Data (the actual value, like 10, 20, etc.)
-
Next pointer (the address of the next node)
-
Here’s a small Python class to represent a Node:
Now, we can link nodes manually:
So in memory, it looks like this:
🧩 Step 3: Head and Tail
To work with a linked list, we use two special pointers:
-
Head → Points to the first node
-
Tail → Points to the last node
Example:
Diagrammatically:
The last node’s next is None, indicating the end of the list.
🧬 Step 4: Linked List in Memory
Unlike Python lists, linked lists are not stored in contiguous memory.
The nodes can be scattered anywhere in memory — but since each node knows where the next one is, we can still traverse the list.
Imagine memory blocks like this:
| Memory Address | Value | Next Address |
|---|---|---|
| 100xA | 10 | 200xB |
| 300xB | 20 | 400xC |
| 500xC | 30 | None |
So even though the data isn’t side-by-side, we can follow the links to reach every node.
⚡ Python List vs Linked List — Key Differences
| Feature | Python List | Linked List |
|---|---|---|
| Memory | Contiguous | Non-contiguous |
| Access by Index | Yes (O(1)) | No (O(n)) |
| Insertion/Deletion | Slow (because of shifting) | Fast (just change pointers) |
| Structure | Array-based | Node-based (with pointers) |
| Traversal | Direct (via index) | Sequential (via next) |
🧰 Example: Traversing a Linked List
Let’s print all values in our linked list:
Output:
🧩 Summary
-
A Linked List is a chain of nodes connected through pointers.
-
It has a head (start) and a tail (end).
-
It does not store elements in contiguous memory.
-
Accessing elements is slower than lists, but inserting or deleting elements is easier.