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
// 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"

// This code is for a LINEAR linked list.
//
// In HW07, you are doing a linear linked list for the warmup, and a circular linked list
// for the main assignment.

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);
    }
}

// TIP:  AVOID SPECIAL CASES

void destroy_list(struct Node** a_head, struct Node** a_tail) {
    while(*a_head != NULL) {
        struct Node* new_head = (*a_head) -> next;
        free(*a_head);
        *a_head = new_head;
    }
    assert(*a_head == NULL); // list must be empty now
    *a_tail = NULL;
}

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

    append(5, &head, &tail);
    append(6, &head, &tail);
    append(7, &head, &tail);
    
    print_list(head);

    destroy_list(&head, &tail);

    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.