C linked nodes and traversal
Connect records with pointers and follow a chain.
On this page
Structs, pointers, and address-of.
- Connect records with pointers and follow a chain.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
A node contains a value and a pointer to the next node. NULL ends the chain. The arrow operator accesses a field through a pointer.
These nodes have automatic storage duration in main, so they remain valid throughout traversal and require no free. A heap-allocated version would need an explicit cleanup policy.
Code example
#include <stdio.h>
struct Node { int value; struct Node *next; };
int main(void) {
struct Node third = {30, NULL};
struct Node second = {20, &third};
struct Node first = {10, &second};
for (struct Node *current = &first; current != NULL; current = current->next) {
printf("%d\n", current->value);
}
return 0;
}10 20 30
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
#include <stdio.h>struct Node { int value; struct Node *next; };int main(void) { struct Node third = {30, NULL}; struct Node second = {20, &third}; struct Node first = {10, &second}; for (struct Node *current = &first; current != NULL; current = current->next) { printf("%d\n", current->value); } return 0;}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Create the tail. | 30 -> NULL | — | |
| Link second to third. | 20 -> 30 -> NULL | — | |
| Link first to second. | 10 -> 20 -> 30 -> NULL | — | |
| Visit first, second, and third in three iterations. | current: &first -> &second -> &third | 10 20 30 | |
| Traversal stops at NULL; main ends the nodes' lifetimes. | current: &first -> &second -> &third | 10 20 30 |
Behind the scenes
How C processes this code
The C compiler produces a native program. Variables occupy memory, and execution enters main.
Cost and common mistakes
O(n) traversal time and O(1) traversal state, excluding n nodes.
- Do not return pointers to local nodes after their function ends.
- A cycle requires a different termination strategy.
Try it yourself
Link first directly to third.
Reveal answer and reasoning
Traversal prints 10 then 30; second still exists but is not reachable from first.