← Retour au cours: C programming from scratch

Dynamic linked list and week 6 review

Vidéo bientôt disponible

This lesson brings together what you learned this week: structs, pointers and dynamic memory. You will build a linked list, a data structure in which each element (node) is reserved separately and holds a pointer to the next one. Unlike an array, it grows and shrinks node by node without copying data, and inserting at the start is instant. In exchange, you cannot access element i directly: you must walk it from the beginning.

The node

A node is a struct with a datum and a pointer to another node of the same type. Since the struct refers to itself, it needs a tag (struct Node) so the pointer can be written inside its own definition. The list is represented by a pointer to the first node, the head; the empty list is a head equal to NULL. The last node has next equal to NULL, which marks the end of the traversal.

c
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int value;
    struct Node *next;
} Node;

/* Inserts at the head. Returns the new head, or NULL on failure. */
static Node *push_front(Node *head, int value) {
    Node *node = malloc(sizeof *node);
    if (node == NULL) {
        return NULL;
    }
    node->value = value;
    node->next = head;
    return node;
}

static void print_list(const Node *head) {
    for (const Node *cur = head; cur != NULL; cur = cur->next) {
        printf("%d -> ", cur->value);
    }
    printf("NULL\n");
}

static void free_list(Node *head) {
    while (head != NULL) {
        Node *next = head->next;   /* save before freeing */
        free(head);
        head = next;
    }
}

int main(void) {
    Node *head = NULL;
    for (int i = 1; i <= 4; i++) {
        Node *updated = push_front(head, i * 10);
        if (updated == NULL) {
            free_list(head);
            return 1;
        }
        head = updated;
    }
    print_list(head);          /* 40 -> 30 -> 20 -> 10 -> NULL */
    free_list(head);
    return 0;
}

Look at free_list: it saves the next node before freeing the current one, because after free you can no longer read head->next. It is the most typical error when writing lists. Notice also that push_front returns the new head: since C passes by value, the function cannot modify the caller's head variable unless you receive a pointer to pointer (Node **head), an alternative you will see in the exercise.

Search and remove

Searching walks the nodes until the value is found. Removing requires reconnecting the list: the previous node must point to the removed node's next, and then the node is freed. The special case is deleting the head, because there is no previous node. Using a pointer to pointer unifies both cases: you point to the link that must be modified, whether it is the head or the next field of a node.

c
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int value;
    struct Node *next;
} Node;

static Node *find(Node *head, int value) {
    for (Node *cur = head; cur != NULL; cur = cur->next) {
        if (cur->value == value) {
            return cur;
        }
    }
    return NULL;
}

/* Removes the first node holding value. Returns 1 if removed. */
static int remove_value(Node **head, int value) {
    for (Node **link = head; *link != NULL; link = &(*link)->next) {
        if ((*link)->value == value) {
            Node *doomed = *link;
            *link = doomed->next;    /* skip the node */
            free(doomed);
            return 1;
        }
    }
    return 0;
}

int main(void) {
    Node *head = NULL;
    for (int i = 3; i >= 1; i--) {
        Node *n = malloc(sizeof *n);
        if (n == NULL) {
            return 1;
        }
        n->value = i;
        n->next = head;
        head = n;
    }
    printf("found 2: %s\n", find(head, 2) ? "yes" : "no");
    printf("removed 2: %d\n", remove_value(&head, 2));
    printf("found 2: %s\n", find(head, 2) ? "yes" : "no");

    while (head != NULL) {
        Node *next = head->next;
        free(head);
        head = next;
    }
    return 0;
}

Week 6 review: malloc, calloc, realloc and free manage the heap; always check NULL, avoid leaks, use after free and double free; a struct groups fields of different types; typedef gives convenient names; p->field accesses through a pointer; and a linked list combines all of it. Do the exercise and the quiz.

Testez vos acquis

Question 1 sur 6

What does malloc return if there is not enough memory?

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →