Skip to main content
Data Structures
CHAPTER 08 Beginner

Singly Linked Lists

Updated: May 17, 2026
15 min read

# CHAPTER 8

Singly Linked Lists

1. Introduction

In the previous chapter, we established the theoretical architecture of a Linked List: independent Nodes connected by a single, forward-facing memory pointer. Because the pointers only go in one direction (Head to Tail), this specific structure is formally known as a Singly Linked List. In this chapter, we transition from theory to heavy algorithmic programming. Manipulating pointers is notoriously difficult and error-prone. A single pointer pointing to the wrong object will detach the entire data chain and crash the software. We will master the core algorithms: Traversal, Insertion, Deletion, and the legendary Reversal.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Write a while loop to traverse a Singly Linked List.
  • Execute pointer manipulation to insert new Nodes at the Head, Tail, and Middle.
  • Securely delete a Node without breaking the memory chain.
  • Solve the "Reverse a Linked List" FAANG interview problem.

3. Traversal (Printing the List)

You cannot use a standard for(i = 0; i < n; i++) loop on a linked list because there are no indexes! You must use a while loop that follows the pointers.
java
1234567891011121314
// Java Example: Traversal Algorithm
public void displayList(Node head) {
    // 1. Create a temporary pointer! NEVER MOVE THE HEAD!
    Node current = head;
    
    // 2. Loop until the pointer falls off the end (NULL)
    while (current != null) {
        System.out.print(current.data + " -> ");
        
        // 3. The most important line: Move pointer to the next node
        current = current.next; 
    }
    System.out.println("NULL");
}

Time Complexity: O(n). We must visit every single node once.

4. Insertion Algorithms

Inserting data requires creating a new Node and carefully rewiring the pointers. The order of operations is critical. Always attach the new Node to the list BEFORE you break the old links!

#### 4.1 Inserting at the Front (The Head) This is the superpower of Linked Lists. It is instantaneously O(1).

python
12345678910
# Python Example: Insert at Head
def insert_at_beginning(self, new_data):
    # 1. Create the new node
    new_node = Node(new_data)
    
    # 2. Point new node's 'next' to the current Head
    new_node.next = self.head
    
    # 3. Officially declare the new node as the permanent Head
    self.head = new_node

#### 4.2 Inserting at the End (The Tail) To insert at the end, you must traverse the entire list to find the final node. This takes O(n) time! *(Note: If you maintain a separate Tail pointer variable in your class, this drops to O(1)!)*

cpp
123456789101112131415161718192021
// C++ Example: Insert at End O(n)
void insertAtEnd(Node** head_ref, int new_data) {
    Node* new_node = new Node();
    new_node->data = new_data;
    new_node->next = NULL;

    // Edge Case: If list is empty, make new node the head
    if (*head_ref == NULL) {
        *head_ref = new_node;
        return;
    }

    // Traverse to the last node
    Node* last = *head_ref;
    while (last->next != NULL) {
        last = last->next;
    }

    // Point the old last node to the brand new node
    last->next = new_node;
}

5. Deletion Algorithms

Deleting a node means rewiring the pointers to "skip over" the target node. Once nothing points to the target node, the Garbage Collector will delete it from RAM.

Deleting a specific value (e.g., delete the node with data '20'):

  1. 1. Traverse the list to find the node *immediately before* the target.
  1. 2. Change the previous node's pointer to point to the node *after* the target.
  1. 3. The target is now completely disconnected.

java
12345678910111213141516171819202122
// Java Example: Delete by Value
public void deleteNode(int key) {
    Node temp = head, prev = null;

    // Edge Case: If the Head itself holds the key
    if (temp != null && temp.data == key) {
        head = temp.next; // Change head
        return;
    }

    // Traverse to find the key
    while (temp != null && temp.data != key) {
        prev = temp;
        temp = temp.next;
    }

    // If key was not present
    if (temp == null) return;

    // Unlink the node from linked list (Skip it!)
    prev.next = temp.next;
}

6. The Ultimate Interview: Reversing a Linked List

This is arguably the most famous software engineering interview question. You must flip all the arrows backward in O(n) time and O(1) space. [1] -> [2] -> [3] -> NULL becomes NULL <- [1] <- [2] <- [3]

You need three pointers: prev, current, and next.

python
1234567891011121314151617181920
# Python Example: Reverse a Linked List (FAANG Standard)
def reverse_list(self):
    prev = None
    current = self.head
    
    while current is not None:
        # 1. Save the next node before we break the link
        next_node = current.next 
        
        # 2. Reverse the pointer! (Point backward to prev)
        current.next = prev 
        
        # 3. Slide the prev pointer forward one step
        prev = current 
        
        # 4. Slide the current pointer forward one step
        current = next_node 
        
    # After loop, 'prev' is sitting on the old Tail. Make it the new Head!
    self.head = prev

7. Complexity Analysis

OperationBest CaseWorst Case
SearchO(1)O(n)
Insert at HeadO(1)O(1)
Insert at TailO(n)O(n) *(O(1) if Tail pointer exists)*
Delete at HeadO(1)O(1)
Delete specific nodeO(1)O(n) (Requires search)

8. Common Mistakes

  • Null Pointer Exceptions: The most common error in pointer logic. If you try to execute current.next but current is already NULL, the program will instantly crash. Always check if (current != null) before accessing properties!
  • Breaking the Chain during Insertion: If you are inserting B between A and C, and you change A.next = B first, you have lost the memory address of C forever. You must do B.next = C first, and then A.next = B. Order matters absolutely.

9. Best Practices

  • Use a Dummy Node: When solving complex linked list algorithms (like merging two lists), creating a temporary "Dummy" head node drastically simplifies the code and prevents edge-case crashes when dealing with empty lists.

10. Exercises

  1. 1. Write a function to find the exact middle node of a Linked List in a single O(n) pass. *(Hint: Use a Slow Pointer and a Fast Pointer that moves twice as fast).*
  1. 2. Walk through the Reversal algorithm on paper with three nodes. Track the prev, curr, and next variables at each step.

11. MCQs with Answers

Question 1

When traversing a Singly Linked List, what is the mandatory mathematical condition required to safely terminate the while loop?

Question 2

When inserting a brand new Node directly into the middle of a Linked List, what is the critical order of pointer reassignment required to prevent catastrophic data loss?

Question 3

What is the standard Time Complexity for inserting a Node at the absolute end (Tail) of a Singly Linked List that only tracks the Head pointer?

Question 4

How can a software architect modify the base Linked List class to reduce Tail Insertion time to O(1)?

Question 5

In the standard algorithm to Reverse a Singly Linked List, what is the explicit architectural purpose of the temporary next_node variable?

Question 6

To safely delete a specific Node from the middle of the list, what pointer modification must occur?

Question 7

What happens if a developer attempts to execute current.next on a Node when current is actually NULL?

Question 8

Why is searching for a specific integer in a Singly Linked List strictly an O(n) operation?

Question 9

When utilizing the "Fast and Slow Pointer" technique (Floyd's Algorithm), the Fast pointer moves 2 steps while the Slow pointer moves 1 step. When the Fast pointer hits NULL, where is the Slow pointer?

Question 10

What is the Space Complexity of reversing a Linked List in-place using pointers?

13. Interview Preparation

Top Interview Questions:
  • *Algorithmic Coding:* "Write an algorithm to detect a 'Cycle' in a Linked List. (A Cycle occurs if the Tail node maliciously points back to a node in the middle of the list, creating an infinite loop)." *(Answer: Use Floyd's Tortoise and Hare algorithm. If the Fast pointer ever equals the Slow pointer, a cycle exists!).*
  • *Algorithmic Coding:* "Write an O(n) algorithm to merge two sorted Linked Lists into a single, perfectly sorted Linked List without creating any new Nodes."

Common Pitfalls:

  • In whiteboard interviews, constantly talking about updating pointers but forgetting to actually return the *new Head* at the very end of the function! If the calling program doesn't get the new Head, the data is useless.

14. FAQs

Q: Can I traverse a Singly Linked List backward from Tail to Head? A: No! Singly Linked Lists only have forward-facing pointers. If you are sitting on the 5th Node, there is absolutely no physical way to know the memory address of the 4th Node. To go backward, we need a new data structure!

15. Summary

You have mastered the most difficult pointer logic in introductory computer science. By orchestrating loops and temporary variables, you can seamlessly traverse, inject, bypass, and reverse scattered memory blocks.

16. Next Chapter Recommendation

The inability to travel backward is a severe limitation for software like Web Browsers (which need a Back button). To solve this, we must double our memory pointers. In Chapter 9: Doubly Linked Lists, we will create nodes that look both forward into the future, and backward into the past.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·