Linked lists: nodes and pointers
A linked list is a chain of nodes, each from malloc, holding data and a next pointer to the following node, scattered on the heap; you walk it with p = p->next until NULL, so getting element i or the length is O(n).
An array needs one block of memory, and inserting or deleting means moving elements. A linked list does it differently: each element is stored on its own, anywhere in memory, and each one remembers "where the next one is". In this lesson you build a singly linked list in C and look closely at nodes, pointers and walking the list.
A node: data plus a pointer
Each item of a linked list is a node:
1typedef struct Node {2 int data; // the number this node holds3 struct Node *next; // address of the next node; NULL in the last4} Node;
The struct holds a pointer to the same kind of struct, so it's written struct Node *next (the name Node isn't defined yet at that point).
What does the last node’s next hold?
What if the node were struct Node { int data; struct Node next; }; (next is not a pointer)? Would that work?
struct Node *next is fine.One malloc per node
Each node gets its own block on the heap from malloc. Their addresses are all over the place, not side by side; next is what links them.
stack
headNode *heap
(Each box is a node; its next holds the next node's address, and head holds the first one's.)
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 int data;6 struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10 Node *n = malloc(sizeof(Node));11 n->data = data;12 n->next = next;13 return n;14}15 16int main(void) {17 Node *c = new_node(9, NULL);18 Node *b = new_node(7, c);19 Node *a = new_node(3, b);20 Node *head = a;21 printf("%d %d %d\n", head->data, head->next->data, head->next->next->data);22 return 0;23}
3 7 9
Press Step and watch the three blocks appear on the heap one by one, linked by their nexts. head->next->next->data is two steps along the pointers.
To keep it short, these nodes live on the stack (a real list uses malloc). What does this program print?
1#include <stdio.h>2 3typedef struct Node {4 int data;5 struct Node *next;6} Node;7 8int main(void) {9 Node c = {9, NULL}, b = {7, &c}, a = {3, &b};10 Node *head = &a;11 printf("%d\n", head->next->next->data - head->next->data);12 return 0;13}
head->next is the 7 node and head->next->next is the 9 node: 9 − 7 = 2. Each extra ->next follows the pointers one more step.Build 3 → 7 → 9 with new_node(data, next). Put these three lines in order: when a node is made, the node its next points to must already exist.
Node *b = new_node(7, c);Node *a = new_node(3, b);Node *c = new_node(9, NULL);
3 7 9
Walking: p = p->next until NULL
Walking a whole linked list is almost always these lines:
p↓1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 int data;6 struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10 Node *n = malloc(sizeof(Node));11 n->data = data;12 n->next = next;13 return n;14}15 16int main(void) {17 Node *head = new_node(3, new_node(7, new_node(9, NULL)));18 for (Node *p = head; p != NULL; p = p->next)19 printf("%d -> ", p->data);20 printf("NULL\n");21 return 0;22}
3 -> 7 -> 9 -> NULL
With the loop condition written as p->next != NULL, what does it print?
1#include <stdio.h>2 3typedef struct Node {4 int data;5 struct Node *next;6} Node;7 8int main(void) {9 Node c = {9, NULL}, b = {7, &c}, a = {3, &b};10 int n = 0;11 for (Node *p = &a; p->next != NULL; p = p->next)12 n++;13 printf("%d\n", n);14 return 0;15}
p->next is already NULL, so the loop stops and 9 isn't counted: only 2. p != NULL means "visit every node"; p->next != NULL means "stop on the last one". Both are common; pick the one you need.Pick what goes in the blank so p walks from node to node and adds up 3 + 7 + 9.
1#include <stdio.h>2 3typedef struct Node {4 int data;5 struct Node *next;6} Node;7 8int main(void) {9 Node c = {9, NULL}, b = {7, &c}, a = {3, &b};10 int sum = 0;11 for (Node *p = &a; p != NULL; p = )12 sum += p->data;13 printf("%d\n", sum);14 return 0;15}
next knows where the next node is: p = p->next. A list’s nodes are scattered in memory, so p + 1 doesn’t work the way it does in an array.How long is it
✓Finish length: walk from head to NULL and count the nodes.
4
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 int data;6 struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10 Node *n = malloc(sizeof(Node));11 n->data = data;12 n->next = next;13 return n;14}15 16int length(Node *head) {17 int n = 0;18 // p from head to NULL19 return n;20}21 22int main(void) {23 Node *head = new_node(5, new_node(1, new_node(4, new_node(2, NULL))));24 printf("%d\n", length(head));25 return 0;26}
Length and search both walk
A linked list has no indexes: to get element i, count your way there from head.
| Operation | Array | Linked list |
|---|---|---|
| Get element i | O(1) | O(n): i steps from the head |
| Length | O(1) (keeps len) | O(n): walk and count (unless it keeps one too) |
| Find a value | O(n) | O(n) |
Where linked lists shine is the next lesson: once you're on a node, inserting or deleting after it is O(1).
Even with the same Big O, an array is often faster in practice: the CPU reads memory a whole stretch at a time (a cache line, usually 64 bytes). An array's next element has most likely come along already; a linked list's next node is somewhere else, often another trip to memory.
The list is head → 5 → 1 → 4 → 2. p starts at head (on the 5). How many p = p->next until p is on the 4?
A singly linked list that keeps only head. Which of these take O(n)? (You can pick more than one.)
Which one is it
✓Finish find: return the position (counting from 1) of the first node equal to x, or 0 if there isn't one.
3 0
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 int data;6 struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10 Node *n = malloc(sizeof(Node));11 n->data = data;12 n->next = next;13 return n;14}15 16int find(Node *head, int x) {17 int i = 1;18 // count as you walk; return i when it equals x19 return 0;20}21 22int main(void) {23 Node *head = new_node(5, new_node(1, new_node(4, new_node(2, NULL))));24 printf("%d %d\n", find(head, 4), find(head, 7));25 return 0;26}
Free it when you're done
Every node came from malloc, so each one needs a free at the end. The order matters: remember next, then free. The other way round, free(p) and then p->next, reads memory that has already been given back.
stack
headNode *nextNode *?heap
Does this free the whole list correctly? for (Node *p = head; p != NULL; p = p->next) free(p);
p = p->next runs after free(p), so it reads a block that has been given back. On a normal computer it may happen to work, or it may crash; the engine here stops and tells you. Save next in a variable first, then free.Give it all back
✓Finish free_all: free every node and return how many were freed. Careful: once a node is freed you can't read its next.
3
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 int data;6 struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10 Node *n = malloc(sizeof(Node));11 n->data = data;12 n->next = next;13 return n;14}15 16int free_all(Node *head) {17 int n = 0;18 // remember the next one, then free this one19 return n;20}21 22int main(void) {23 Node *head = new_node(5, new_node(1, new_node(4, NULL)));24 printf("%d\n", free_all(head));25 return 0;26}
Summary
A linked list: nodes scattered on the heap, linked by next
- node = data + the next node's address; NULL in the last
- Walk: for (p = head; p != NULL; p = p->next)
- No indexes: getting element i and the length are O(n)
- Remember next before you free
1typedef struct Node { int data; struct Node *next; } Node;2for (Node *p = head; p != NULL; p = p->next)3 printf("%d ", p->data);