🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Singly Linked Lists — Nodes, Traversal, Insertion — Complete Beginner Guide

Data Structures FoundationsSingly Linked Lists — Nodes, Traversal, Insertion🟢 Free Lesson

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.

python
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).

python
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 SpotCostWork Needed
FrontO(1)Relink head
After known nodeO(1)Relink two pointers
By position indexO(n)Walk to that spot
Tail with tail pointerO(1)Relink tail
Tail without tail pointerO(n)Walk to the end
python
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).

python
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

TaskArray or Dynamic ArraySingly Linked List
Index accessO(1)O(n)
Search unsortedO(n)O(n)
Insert at frontO(n)O(1)
Insert after known nodeO(n)O(1)
Extra per itemLowPointer overhead
Cache behaviorStrongWeaker

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.

python
# 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

  1. Explain why accessing the k-th element of a singly linked list is O(n).
  2. Write the steps to insert a node after an existing node in O(1) time.
  3. 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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Data Structures Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement