C · Course navigation

C linked nodes and traversal

Connect records with pointers and follow a chain.

On this page
Before you start

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

C
#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;
}
Output
10
20
30

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1#include <stdio.h>
2struct Node { int value; struct Node *next; };
3int main(void) {
4 struct Node third = {30, NULL};
5 struct Node second = {20, &third};
6 struct Node first = {10, &second};
7 for (struct Node *current = &first; current != NULL; current = current->next) {
8 printf("%d\n", current->value);
9 }
10 return 0;
11}

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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading