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

//void print_linked_list(Node* head, void (*print_value_fn)(char*)) {
void print_linked_list(Node* head, void (*print_value_fn)(void*)) {
    for (Node* cur = head; cur != NULL; cur = cur->next) {
        printf("[");
        print_value_fn(cur->a_value);
        printf("]");
        printf("%s", cur->next == NULL ? "\n" : "->");
    }
}

// appends a new value to the linked list after the tail
// mallocing a new node and updating the tail
// works with any size of linked list
void append(void* a_value, Node** a_head, Node** a_tail) {
    // step 1: malloc new node
    Node* new_node = malloc(sizeof(*new_node));
    // step 2: initialize new node
    *new_node = (Node) { .a_value = a_value, .next = NULL };

    // step 3: insert new node into list
    // case 1: list is size 0
    // POTENTIAL BUG: a_head should never be NULL
    //               *a_head might be NULL
    if (*a_head == NULL) {
        // new node is both the new head and new tail
        *a_head = new_node;
    }
    // case 2: list is size > 0
    else {
        // append to the end of the old tail
        (*a_tail)->next = new_node;
        // potential bug: -> has higher precedence than *
        //*a_tail->next = new_node;
    }
    // step 4: update the tail
    // always make the new node the new tail
    *a_tail = new_node;
}

void destroy_linked_list(Node** a_head, Node** a_tail) {
    Node* cur = *a_head;
    while (cur != NULL) {
        Node* next = cur->next;
        free(cur);
        cur = next;
    }
    *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.