Singly Linked Lists — Nodes, Traversal, Insertion — Complete Beginner Guide
Learning Objectives
- Build a node with value and next pointer
- Traverse a linked list from the head
- Insert at head, tail, or middle
- Delete a target node safely
- Compare list costs with array costs
What Is a Singly Linked List?
A singly linked list stores items in nodes. Each node holds a value and a pointer to the next node. The list keeps a reference to the head, the first node. The last node points to nothing.
Unlike arrays, nodes need not sit next to each other in memory. Order lives in the pointers, not in address math.
class Node:
def __init__(self, value):
self.value = value
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def push_front(self, value):
node = Node(value)
node.next = self.head
self.head = node
def to_list(self):
out = []
current = self.head
while current is not None:
out.append(current.value)
current = current.next
return out
ll = SinglyLinkedList()
ll.push_front(30)
ll.push_front(20)
ll.push_front(10)
print(ll.to_list()) # 10, 20, 30
Traversal
Traversal starts at head and follows next until the pointer is empty. Every step visits one node, so a full walk is O(n).
def print_list(head):
current = head
while current is not None:
print(current.value, end=" -> ")
current = current.next
print("None")
You cannot jump to the middle in one step. Index access is O(n), unlike the O(1) of arrays.
Insertion
Insertion cost depends on where you already hold a reference.
| Insert Spot | Cost | Work Needed |
|---|---|---|
| Front | O(1) | Relink head |
| After known node | O(1) | Relink two pointers |
| By position index | O(n) | Walk to that spot |
| Tail with tail pointer | O(1) | Relink tail |
| Tail without tail pointer | O(n) | Walk to the end |
def insert_after(node, value):
new_node = Node(value)
new_node.next = node.next
node.next = new_node
def insert_at_index(head, index, value):
if index == 0:
new_node = Node(value)
new_node.next = head
return new_node
current = head
position = 0
while current is not None and position < index - 1:
current = current.next
position += 1
if current is None:
return head
new_node = Node(value)
new_node.next = current.next
current.next = new_node
return head
Deletion
To delete, find the previous node and relink around the target. Without a previous pointer, you walk from the head, making search O(n).
def delete_value(head, target):
if head is None:
return None
if head.value == target:
return head.next
current = head
while current.next is not None:
if current.next.value == target:
current.next = current.next.next
return head
current = current.next
return head
Arrays versus Linked Lists
| Task | Array or Dynamic Array | Singly Linked List |
|---|---|---|
| Index access | O(1) | O(n) |
| Search unsorted | O(n) | O(n) |
| Insert at front | O(n) | O(1) |
| Insert after known node | O(n) | O(1) |
| Extra per item | Low | Pointer overhead |
| Cache behavior | Strong | Weaker |
Choose linked lists when front inserts dominate and random index reads do not.
Classic Linked List Patterns
Interviews love linked lists because pointer work builds strong mental models. The slow and fast pointer technique detects a cycle when the fast runner laps the slow one. The same idea finds the middle node in one pass and can locate the k-th node from the end with a k step head start.
Reversing a list is another staple: walk forward while flipping each next pointer, then move both markers ahead. Dummy head nodes remove special-case code when inserting or deleting near the front.
# Reverse a singly linked list in place
def reverse_list(head):
prev = None
current = head
while current is not None:
nxt = current.next
current.next = prev
prev = current
current = nxt
return prev
# Build 1 -> 2 -> 3 then reverse
n3 = type("N", (), {"value": 3, "next": None})()
n2 = type("N", (), {"value": 2, "next": n3})()
n1 = type("N", (), {"value": 1, "next": n2})()
new_head = reverse_list(n1)
print(new_head.value) # 3
Practice drawing boxes and arrows on paper until pointer updates feel automatic.
Pointer Drawing Discipline
Linked list bugs almost always come from losing track of where references point. Adopt a drawing habit: one box per node with value on top and next arrow below. Before you assign, draw the new arrow. After you assign, erase the old one.
For front insert, the order is create node, point new node to current head, then move head to the new node. Reverse that final two steps and you have lost the list. For deletion after a known node, draw the bypass arrow from previous to next before dropping the old pointer.
Interview tip: talk while you draw. Explaining the pointer rewiring out loud demonstrates control even if your first code draft needs a fix. Employers care that you can reason about memory links, not just recite a snippet from a textbook page. Keep a scrap of paper beside your keyboard during practice until arrows feel automatic.
Key Takeaways
💡
- Nodes store a value plus a next pointer
- Head is the entry point for all operations
- Full traversal and unsorted search are O(n)
- Front insert is O(1) if you already hold the head
- Arrays win at indexing; lists win at relinking
Practice Questions
- Explain why accessing the k-th element of a singly linked list is O(n).
- Write the steps to insert a node after an existing node in O(1) time.
- Give one practical use case where a linked list beats a dynamic array.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions