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 | // Okay to copy/adapt for HW07 in ECE 26400 Spring 2020.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
// Declare a "struct type" called "struct Node" for a linked list of ints.
struct Node { // On our platform…
int value; // 4 bytes
struct Node* next; // 8 bytes
}; // entire object: 12 bytes
// Naming: struct type name should be capitalized came case like
// Node (or in other assignments, ListNode, PersonNode, etc.).
int main(int argc, char* argv[]) {
// Create linked list with one node (.value = 5).
struct Node* head = malloc(sizeof(*head));
(*head) = (struct Node) { .value = 5, .next = NULL };
// ↑ ↑ ↑ Use a COMPOUND LITERAL like this ↑ ↑ ↑
// Print contents of the list, still with size=1.
printf("head -> value == %d\n", head -> value);
printf("head -> next == %p\n", (void*)head -> next);
// Create a second node.
struct Node* new_node = malloc(sizeof(*new_node));
(*new_node) = (struct Node) { .value = 6, .next = NULL };
// Connect the tail of the second node (head -> next) to the new node (new_node).
head -> next = new_node;
// Print contents of the list, now with size=2.
printf("head -> value == %d\n", head -> value);
printf("head -> next == %p\n", (void*)head -> next);
printf("new_node -> value == %d\n", new_node -> value);
printf("new_node -> next == %p\n", (void*)new_node -> next);
// Free both nodes
free(head -> next);
free(head);
return EXIT_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////
// Question from after class (2/25/2020):
//
// Q: What if you connect the last node (tail) to the first node (head)?
// … like this:
// new_node -> next = head;
//
// A: That would be a circular linked list. The above example is
// a linear linked list which is the common case.
/////////////////////////////////////////////////////////////////////////////////////
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2020 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.