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 | #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 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);
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.