/***************************************************************************** * linkedlists.c * CSCI E-52 * Mathew Chartier * * Applying structs to the creation and management of linked lists. *****************************************************************************/ #include #include // Singly-Linked Lists struct slnode { // The value we are storing int val; // A pointer to the next node in the linked list struct slnode *next; }; /* * void * append(int new_val, struct slnode *node) * * Insert a new value at the end of a singly-linked list */ void append(int new_val, struct slnode **list_start) { // Allocate memory for the node and initialize values struct slnode *new_node = malloc(sizeof(struct slnode)); if (new_node == NULL) { printf("ERROR: Unable to allocate memory.\n"); return; } new_node->val = new_val; new_node->next = NULL; if (*list_start == NULL) { *list_start = new_node; return; } struct slnode *list_ptr = *list_start; while (list_ptr->next != NULL) list_ptr = list_ptr->next; // Append our new node list_ptr->next = new_node; } void print_list(struct slnode *list_ptr) { printf("List: "); while(list_ptr != NULL) { printf("%d ", list_ptr->val); list_ptr = list_ptr->next; } printf("\n"); } int main(int argc, char *argv[]) { struct slnode *list = NULL; append(4, &list); append(8, &list); append(15, &list); append(16, &list); append(23, &list); append(42, &list); print_list(list); }