Data Structures•Easy
Traversal
Traversal
Traversal means visiting every node in the list exactly once, starting from the head and following next pointers until NULL is reached.
The Core Pattern
Node* temp = head; // start at head
while (temp != NULL) { // loop until end
// process temp->data
temp = temp->next; // move forward
}
What can you do during traversal?
| Goal | Action per node |
|---|---|
| Print all values | printf("%d", temp->data) |
| Count nodes | count++ |
| Find max value | if (temp->data > max) max = temp->data |
| Search for a value | if (temp->data == key) return temp |
| Sum all values | sum += temp->data |
Time & Space
- Time: O(N) — must visit all N nodes
- Space: O(1) — only uses one extra pointer (
temp), regardless of list size
The
temppointer is just a cursor. Movingtempdoes NOT modify the original list.