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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
typedef struct _Node {
int value;
struct _Node* next; // have to use cannonical name (struct _Node) for this part
} Node;
void print_list_of_ints(Node* head) {
for(Node* curr = head; curr != NULL; curr = curr -> next) {
printf("[%d] ", curr -> value);
}
}
void destroy_list(Node** a_head, Node** a_tail) {
while(*a_head != NULL) {
// 1. Save a copy of the second node (or NULL if size is 1). This will become
// the new head.
Node* new_head = (*a_head) -> next; // new head will be the second node in the list
// 2. Free the old head.
free(*a_head); // free the old head.
// 3. Set the head to the new_head.
*a_head = new_head; // IMPORTANT: This must come last.
}
assert(*a_head == NULL);
// 4. Set the tail to NULL.
*a_tail = NULL;
}
void append(int value, Node** a_head, Node** a_tail) {
// 1. Allocate memory for new tail.
Node* new_tail = malloc(sizeof(*new_tail));
// 2. Initialize fields of new tail. .next of tail is always NULL.
*new_tail = (Node) { .value = value, .next = NULL };
// 3. Depending on if list is initially empty or not…
if(*a_head == NULL) { // List is initially EMPTY
// … Set the head to the new node. We now have a list of size 1, or…
*a_head = new_tail; // a_head is a Node**. *a_head is a Node*. new_tail is a Node*.
}
else { // List is initially NOT empty
// … Connect the old tail to the new tail. Without this, we'd have separate lists.
(*a_tail) -> next = new_tail;
}
// 4. Set the tail to the new tail.
*a_tail = new_tail;
// IMPORTANT: This must be last. Otherwise, you won't be able to connect the old
// tail to the new tail.
}
int main(int argc, char* argv[]) {
Node* head = NULL;
Node* tail = NULL;
append(10, &head, &tail); // [10]
append(11, &head, &tail); // [10]→[11]
append(12, &head, &tail); // [10]→[11]→[12]
print_list_of_ints(head);
destroy_list(&head, &tail);
assert(head == NULL); // head must be NULL right after destroying the list.
assert(tail == NULL); // tail " " " " " " " "
return EXIT_SUCCESS;
}
/* 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.