Kodewick
Start learning →
Linked lists: nodes and pointers7 / 50

Linked lists: nodes and pointers

Lesson 7 of 50 · Part 2 · Arrays and linked lists · about 14 minutes

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).

3a
NULL
One node: data holds 3, next holds NULL (nothing comes after it)
Choose one

What does the last node’s next hold?

Choose one

What if the node were struct Node { int data; struct Node next; }; (next is not a pointer)? Would that work?

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

0x5a403Node
0x5a107Node
0x5a909Node
Three nodes scattered on the heap, linked into 3 → 7 → 9 by the addresses in next

(Each box is a node; its next holds the next node's address, and head holds the first one's.)

main.c
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}
Output
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.

Guess the outputA wrong guess is fine

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}
Put in orderDrag, or use the arrows

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.

  1. Node *b = new_node(7, c);
  2. Node *a = new_node(3, b);
  3. Node *c = new_node(9, NULL);
Should print
3 7 9

Walking: p = p->next until NULL

Walking a whole linked list is almost always these lines:

p↓
3a
7b
9c
NULL

Walking: p starts at head, p = p->next each time, and stops at NULL
main.c
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}
Output
3 -> 7 -> 9 -> NULL
Guess the outputA wrong guess is fine

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}
Fill inTap one to fill a blank; tap a blank to take it back

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}
Exercise 1

How long is it

Finish length: walk from head to NULL and count the nodes.

It should print
4
exercise1.c
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}
Output
Press Run or Ctrl+Enter

Length and search both walk

A linked list has no indexes: to get element i, count your way there from head.

OperationArrayLinked list
Get element iO(1)O(n): i steps from the head
LengthO(1) (keeps len)O(n): walk and count (unless it keeps one too)
Find a valueO(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).

The same 3 7 9 4: above, the array, one slot after another from 0x1000; below, the linked list's 4 nodes scattered over the heap, each next pointing at the following one, the last NULL

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.

Choose one

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?

Choose allPick all that apply

A singly linked list that keeps only head. Which of these take O(n)? (You can pick more than one.)

Exercise 2

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.

It should print
3 0
exercise2.c
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}
Output
Press Run or Ctrl+Enter

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

3Node
7Node
9Node

Freeing a whole list: each round, next remembers the following node, then the current one is freed; in step 2 head turns red, which means "given back, don't read it"
Choose one

Does this free the whole list correctly? for (Node *p = head; p != NULL; p = p->next) free(p);

Exercise 3

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.

It should print
3
exercise3.c
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}
Output
Press Run or Ctrl+Enter

Summary

Take-away

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);