1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

typedef struct _Node {
    int value;
    struct _Node* next;  // have to use cannonical name (struct _Node) for this part
} Node;

void print_list_of_ints(Node* head) {
    for(Node* curr = head; curr != NULL; curr = curr -> next) {
        printf("[%d] ", curr -> value);
    }
}

void destroy_list(Node** a_head, Node** a_tail) {
    while(*a_head != NULL) {
        // 1. Save a copy of the second node (or NULL if size is 1).  This will become
        //    the new head.
        Node* new_head = (*a_head) -> next;  // new head will be the second node in the list
        
        // 2. Free the old head.
        free(*a_head);  // free the old head.

        // 3. Set the head to the new_head.
        *a_head = new_head;  // IMPORTANT:  This must come last.
    }
    assert(*a_head == NULL);

    // 4. Set the tail to NULL.
    *a_tail = NULL;
}

void append(int value, Node** a_head, Node** a_tail) {
    // Allocate new node.
    Node* new_tail = malloc(sizeof(*new_tail));

    *new_tail = (Node) { .value = value, .next = NULL };

    if(*a_head == NULL) {
        *a_head = new_tail;
    }
    else {
        (*a_tail) -> next = new_tail;
    }

    *a_tail = new_tail;
}

int main(int argc, char* argv[]) {
    Node* head = NULL;
    Node* tail = NULL;
    append(10, &head, &tail);  // [10]
    append(11, &head, &tail);  // [10]→[11]
    append(12, &head, &tail);  // [10]→[11]→[12]

    print_list_of_ints(head);

    destroy_list(&head, &tail);
    assert(head == NULL); // head must be NULL right after destroying the list.
    assert(tail == NULL); // tail "    "  "    "     "     "          "   "

    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2022 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.