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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "append.h"
#include <assert.h>

void append(int value, Node** a_head, Node** a_tail) {
    Node* new_tail = malloc(sizeof(*new_tail));
    *new_tail = (Node) { .value = value, .next = NULL };
    if(*a_head == NULL) {  // List is empty.  Make it a list of size 1.
        *a_head = new_tail;
    }
    else {  // List is not empty.  Append to the end.
        (*a_tail) -> next = new_tail;
    }
    *a_tail = new_tail;

    assert((*a_tail) -> value == value);
    assert((*a_tail) -> next  == NULL);
    assert((*a_head) != NULL);  // Because if we added anything, list is not empty.
}

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

void destroy_list(Node** a_head, Node** a_tail) {
    for( ; *a_head != NULL; *a_head = new_tail) {
        // Save the new head
        Node* new_head = (*a_head) -> next;

        // Free the old head
        free(*a_head);
    }

    assert(*a_head == NULL);

    *a_tail = NULL;
}
/* 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.