C in 100 Seconds: Linked List Traverse
Video: C in 100 Seconds: Linked List — Traverse, Count, Search | Episode 44 by Taught by Celeste AI - AI Coding Coach
Watch full page →Linked List — Traverse, Count, Search
Every linked list operation is built on traversal — walking from head to NULL. Here are three useful variations.
Count Nodes
int count_nodes(Node *head) {
int count = 0;
Node *c = head;
while (c != NULL) {
count++;
c = c->next;
}
return count;
}
Same while loop as print, but increment a counter instead of printing. Returns the total number of nodes.
Search by Value
int search(Node *head, int value) {
Node *c = head;
int index = 0;
while (c != NULL) {
if (c->data == value) return index;
index++;
c = c->next;
}
return -1;
}
Walk the list and check each node's data. Return the index when found, or -1 if the value is not in the list.
Get by Index
int get_at(Node *head, int index) {
Node *c = head;
for (int i = 0; i < index && c != NULL; i++) {
c = c->next;
}
if (c != NULL) return c->data;
return -1;
}
Advance exactly index times using a for loop. The NULL check prevents crashing on out-of-bounds indexes.
Student Code
Try it yourself: episode44/traverse.c