DSA Day 90: Traversing and Printing a Linked List

📅 Date: August 15, 2026

🧠 Mood: The Navigator 🧭

🔥 Topic: DSA Day 90: Traversing and Printing a Linked List

🔦 Lighting Up the Dark Memory

For the past two days, we have been blindly pushing nodes into heap memory. We know the pushFront and pushBack logic is solid, but without visual confirmation, debugging a data structure is practically impossible. As an engineering student, I've learned that if you can't output it to the console, it essentially doesn't exist.

Today, we wrote the traversal logic to Print the Linked List. In a standard array, printing is as simple as running a for loop with an index counter i. But Linked Lists don't have indexes. They are connected by memory addresses. To read them, we have to physically hop from one node to the next.


🛑 The Golden Rule of Traversal

There is exactly one catastrophic mistake you can make when traversing a linked list: Moving the Head Pointer.

1. The Temporary Explorer

If you write head = head->next to iterate through your list, you permanently lose the start of your chain. The memory before it becomes orphaned. Instead, you must create a temporary pointer that acts as a scout. You set this temp pointer to the head, and then move that pointer forward.

2. Knowing When to Stop

How do you know you've reached the end? The very last node (the Tail) points to NULL. So, your while loop must continue running strictly under the condition that temp != NULL.


💻 The C++ Traversal Implementation

void printList() {
    // 1. Create a scout pointer starting at the head
    Node* temp = head;

    // Edge Case: Empty List
    if (head == NULL) {
        cout << "Linked List is empty!" << endl;
        return;
    }

    // 2. Traverse until you hit the end (NULL)
    while (temp != NULL) {
        // Print the data inside the current node
        cout << temp->data << " -> ";
        
        // 3. Move the scout pointer to the next node
        temp = temp->next;
    }
    
    // Visually terminate the chain
    cout << "NULL" << endl;
}

Performance Breakdown: Because we have to visit every single node exactly one time to print its data, this operation inherently runs in $O(N)$ Time Complexity. We only create one extra pointer (temp), so the Space Complexity is $O(1)$.


🎯 Full Visibility

Finally, we can actually see the structure we've been building in memory. With Push Front, Push Back, and Print fully operational, the basics are covered. Tomorrow, we level up the difficulty by inserting a node straight into the middle of the chain.

No comments:

Post a Comment