// This program demonstrates what happens when you have a linked list inside // a struct and how to access the different elements (like in your assignment). //Sasha Vassar Week09 Lecture 15 #include #include struct list { struct number *numbers; struct letter *letters; }; struct number { int data; struct number *next_number; }; struct letter { char letter; struct letter *next_letter; }; //Function prototypes for some of the functions that we will create struct list *create_list(); struct number *create_number (int data); int add_number(struct list *list_start, int data); void print_numbers(struct list *list_start); // You can see if you can create the bottom two of these functions as practice struct letter *create_letter (char letter); int add_letter(struct list *list_start, char letter); int main (void) { //TODO: We need to create our list structure to house everything first struct list *list_start = create_list(); //Add some numbers to out list add_number(list_start, 1); add_number(list_start, 2); add_number(list_start, 3); //Print the list print_numbers(list_start); return 0; } //Function to create the list struct list *create_list(){ //TODO: Allocate space to the list struct list *new_list = malloc(sizeof(struct list)); //TODO: Initialise the new list new_list->numbers = NULL; new_list->letters = NULL; return new_list; } //Function that creates a new number (node) struct number *create_number (int number) { //Allocate some memory for a new node struct number *new_number = malloc(sizeof(struct number)); //TODO: Initialise the new node new_number->data = number; new_number->next_number = NULL; return new_number; } //Function to add a number to the list int add_number(struct list *list_start, int number){ //Make the number node that you will be adding in struct number *new_number = create_number(number); //TODO: Create a current pointer to keep track of where we are in the list //and set it to the head of the numbers list (since we are adding a number) struct number *current = list_start->numbers; //TODO: Boundary case: What if there are no other items in the list? //We will make the new number the head of the list if (current == NULL){ list_start->numbers = new_number; return 0; } //TODO: Otherwise, insert at the end of the list while (current->next_number != NULL) { current = current->next_number; } //I am standing at the last node/on the last node current->next_number = new_number; new_number->next_number = NULL; return 0; } //Function to print the numbers void print_numbers(struct list *list_start) { //TODO: Create a current pointer and set it to the start of the numbers //list (so the head) struct number *current = list_start->numbers; while (current != NULL) { printf("%d -> ", current->data); current = current->next_number; } printf("X\n"); }