//This is the implementation file // It implements the functions in the header file #include #include #include "linked_list.h" //Define a node struct node { int data; struct node *next; }; //Function that creates a node struct node *create_node(int data, struct node *next) { //create a pointer to a node of type struct node //by using malloc to allocate memory struct node *new_node = malloc(sizeof(struct node)); //Initialise the data by setting it to the given int new_node->data = data; //Initialise next pointer to point to the next node given new_node->next = next; return new_node; } //Function that prints a list void print_list(struct node *head) { //create a way to keep track of where we are in the list struct node *current = head; while (current != NULL) { printf("%d -> ", current->data); current = current->next; } printf("X\n"); } void print_list_recursive(struct node *head) { //STOPPING CASE //RECURSIVE CASE if (head == NULL) { printf("X\n"); } else { printf("%d -> ", head->data); print_list_recursive(head->next); } } struct node *insert_endnode(int data, struct node *head) { //create a pointer and point it to the head of the list //that will keep track of where you are struct node *current = head; //create the new node that you want to insert by using //the create_node function we wrote last week struct node *new_node = create_node(data, NULL); //Loop through until you get to the last node in the list //You want to stop at the last node and not go past it while (current->next != NULL) { current = current->next; } //Set the new node as the last node, but pointing the current node to it current->next = new_node; new_node->next = NULL; return head; } //Function that adds node at the end of the list struct node *insert_end(struct node *head, int data) { //STOPPING CASE if (head == NULL) { return create_node(data, NULL); } //RECURSIVE CASE head->next = insert_end(head->next, data); return head; } //Function to sum up the nodes of a linked list int sum_list(struct node *head) { int sum = 0; struct node *current = head; while (current != NULL) { sum = sum + current->data; current = current->next; } return sum; } int sum_list_recursive(struct node *head) { //1. Stopping case? head == NULL //2. Recursive case? ??? sum = head->data + head->next->data if (head == NULL) { //STOPPING CASE return 0; } else { //RECURSIVE CASE int sum = head->data + sum_list_recursive(head->next); return sum; } }