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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
// You should follow the same pattern for append and free_list(…), but 
// please write it on your own.  It is okay if it comes out very similar
// But if you were to copy, you would end up in a hole.

// Declare/define a struct type called 'struct _Node' -OR- 'Node' (two names).
typedef struct _Node {
    int value;  // ----     4 bytes for .value
    struct _Node* next; //  8 bytes for .next
} Node;                 // 12 bytes for Node object

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

void free_list(Node** a_head, Node** a_tail) {
    while(*a_head != NULL) {  // while list not empty
        Node* old_head = *a_head;     // Detach head
        *a_head = (*a_head) -> next;  // head becomes 2nd node
        free(old_head);  // Free your mind (head)
    }
    assert(*a_head == NULL);
    *a_tail = NULL;
}

void append(int value, Node** a_head, Node** a_tail) {
    Node* new_tail = malloc(sizeof *new_tail); // Allocate space for new tail (new node)
    *new_tail = (Node) { .value = value, .next = NULL }; // Initialize new tail (new node)
    if(*a_head == NULL) {  // If list is currently empty, then new tail becomes head
        *a_head = new_tail;
    }
    else {
        (*a_tail) -> next = new_tail; // If list not empty, attach new tail after old tail
    }
    *a_tail = new_tail;  // In any case, new_tail becomes the tail, obviously.
}

int main(int argc, char* argv[]) {
    Node* head = NULL;
    Node* tail = NULL;        // now size == 0 (empty list)

    append(5, &head, &tail);  // now size == 1
    append(6, &head, &tail);  // now size == 2
    append(7, &head, &tail);  // now size == 3
    print_list(head);
    free_list(&head, &tail);
    return EXIT_SUCCESS;
}
// Fill in memory form for line 49 --- just before append(7, …, …) returns.
// There will be 3 nodes in the list.

/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

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