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 | #include <stdio.h>
#include <stdlib.h>
struct Node { // LINKED LIST NODE
int value;
struct Node* next;
};
struct Node* create_node(int value) { // WARNING: We will need to free(…)
struct Node* new_node = malloc(sizeof(*new_node));
new_node -> value = value;
new_node -> next = NULL;
return new_node;
}
int main(int argc, char* argv[]) {
// Create a linked list of size 2.
struct Node* head = create_node(10);
head -> next = create_node(12);
// Insert a node with 11 after the head.
struct Node* new_node = create_node(11);
new_node -> next = head -> next;
head -> next = new_node; // <<<< DRAW MEMORY UNTIL HERE (after this line) <<<<<<
// Print contents of linked list ... USE FOR LOOP NOT WHILE(...)
for(struct Node* curr = head; curr != NULL; curr = curr -> next) {
printf("curr -> value == %d\n", curr -> value);
}
// Delete the entire list.
while(head != NULL) { // Do not simply say while(head) { … }
struct Node* new_head = head -> next;
// free(head); // SABOTAGE!!! Deliberately "forget" to free(…)
head = new_head;
}
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2019 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.