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
67
68
69
70
71
72
73
74
// Okay to copy/adapt for HW07 in ECE 26400 Spring 2020.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "clog.h"

struct Node {
    int value;
    struct Node* next;
}; // Don't forget the SEMICOLON!!!


void append(int value, struct Node** a_head, struct Node** a_tail) {
    struct Node* new_node = malloc(sizeof(*new_node));
    *new_node = (struct Node) { .value=value, .next=NULL };

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


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


int main(int argc, char* argv[]) {
    // Empty list
    struct Node* head = NULL; // This is it.  This is an empty list.
    struct Node* tail = head;
    log_addr(head);
    log_addr(tail);

    append(5, &head, &tail);

    log_msg("After adding one node (.value=5)\n");
    log_addr(head);
    log_addr(tail);
    log_int(head -> value);
    log_int(tail -> value);
    
    append(6, &head, &tail);
    log_msg("After adding a second node (.value=6)\n");
    log_addr(head);
    log_addr(tail);
    log_int(head -> value);
    log_int(tail -> value);
    
    append(7, &head, &tail);
    log_msg("After adding a third node (.value=7)\n");
    log_addr(head);
    log_addr(tail);
    log_int(head -> value);
    log_int(tail -> value);
    
    print_list(head);

    // TODO:  destroy_list(…)

    // Currently, we have a MEMORY LEAK because we did not free the memory for
    // these linked list nodes.

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

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