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 75 76 77 78 79 80 81 82 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
typedef struct _Node { // canonical name struct _Node
int value;
struct _Node* next; // need to use canonical name
// invalid: Node* next;
/*
linked_list.c:8:2: error: unknown type name ‘Node’
Node* next;
^~~~
*/
} Node; // shortcut name: Node
void print_linked_list(Node* head) {
// loop to iterate the linked list
// we could write this as a while loop
// per CQ, its better to write as a for loop
for (Node* cur = head; cur != NULL; cur = cur->next) {
printf("[%d]", cur->value);
printf("%s", cur->next == NULL ? "\n" : "->");
}
}
int main(int argc, char* argv[]) {
// linked list of size 0
// NULL
Node* head = NULL;
Node* tail = NULL;
print_linked_list(head);
// linked list of size 1
// [5]->NULL
Node* new_node = malloc(sizeof(*new_node));
*new_node = (Node) { .value = 5, .next = NULL };
// size 0 to 1: replace both head and tail (were NULL before)
head = new_node;
tail = new_node;
print_linked_list(head);
// linked list of size 2
// [5]->[7]->NULL
new_node = malloc(sizeof(*new_node));
*new_node = (Node) { .value = 7, .next = NULL };
// size N to N+1: add new node to the end of tail
tail->next = new_node;
// make new node the new tail
tail = new_node;
// head will never change once first set unless we remove nodes
// tail changes every time we append a node
print_linked_list(head);
// linked list of size 3
// [5]->[7]->[9]->NULL
new_node = malloc(sizeof(*new_node));
*new_node = (Node) { .value = 9, .next = NULL };
// size N to N+1: add new node to the end of tail
tail->next = new_node;
// make new node the new tail
tail = new_node;
print_linked_list(head);
// linked list of size 4
// [5]->[7]->[9]->[1]->NULL
new_node = malloc(sizeof(*new_node));
*new_node = (Node) { .value = 1, .next = NULL };
// size N to N+1: add new node to the end of tail
tail->next = new_node;
// make new node the new tail
tail = new_node;
print_linked_list(head);
// a later node in a linked list is a valid linked list
print_linked_list(head->next);
// TODO: need to free the linked list
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.