Lesson 2 of 14
Print a List
Traversing a Linked List
To visit every node, start at head and follow next pointers until you hit NULL:
void print_list(struct Node *head) {
struct Node *cur = head;
while (cur != NULL) {
printf("%d\n", cur->val);
cur = cur->next;
}
}
This is the fundamental linked list loop. It runs in O(n) time.
The Pattern
Every linked list traversal follows this pattern:
struct Node *cur = head;
while (cur != NULL) {
// do something with cur->val
cur = cur->next;
}
Notice:
- Start
curathead(don't modifyhead— you'd lose the list!) - Check
cur != NULLbefore accessingcur->val - Advance with
cur = cur->nextat each step
Printing vs. Modifying
When you only need to read the list, use a local pointer (cur) instead of moving head. Once head advances past a node, you can't get back to it.
Your Task
Implement void print_list(struct Node *head) that prints each node's value on its own line.
TCC compiler loading...
Loading...
Click "Run" to execute your code.