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 | #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) {
assert((*a_head == NULL) && (*a_tail == NULL)
|| (*a_head != NULL) && (*a_tail != NULL));
// assert((*a_head == NULL) == (*a_tail == NULL)); // shorter version of the above
// Create (and initialize) new tail.
Node* new_tail = malloc(sizeof(*new_tail));
*new_tail = (Node) { .value = value, .next = NULL };
// Connect the new node to the list.
if(*a_head == NULL) {
// List is empty, so 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;
// Sanity checks
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) {
while(*a_head != NULL) {
// Save the new head
Node* new_head = (*a_head) -> next;
// Free the old head
free(*a_head);
// Set 'head' to the address of new head
*a_head = new_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.