// Q1 Programming Quiz - Solution // Author: Chris Wilcox // Date: 12/6/2015 // Class: CS270 // Email: wilcox@cs.colostate.edu // Include files #include "Q1.h" // Global variables Student *head = NULL; Student *tail = NULL; // Read a file void readFile(char *filename) { // Open file FILE *file = fopen(filename, "r"); char name[80]; int id = 0; float gpa = 0.0; // Read file while (fscanf(file, "%s %d %f\n", name, &id, &gpa) == 3) { // Insert student insertStudent(name, id, gpa); } // Close file fclose(file); } // Insert student void insertStudent(char *name, int id, float gpa) { // Allocate new Student Student *new = malloc(sizeof(Student)); new->name = strdup(name); new->id = id; new->gpa = gpa; new->next = NULL; // Check head if (head == NULL) { // Create list head = new; tail = new; } else if (strcmp(head->name, name) > 0) { // Insert head new->next = head; head = new; } else if (strcmp(tail->name, name) < 0) { // Insert tail tail->next = new; tail = new; } else { // Insert middle Student *previous = head; Student *current = head->next; // Search list while (current) { // Check entry if (strcmp(current->name, name) > 0) { // Insert previous previous->next = new; new->next = current; break; } // Advance pointers previous = current; current = current->next; } } } // Remove student void removeStudent(char *name) { Student *temp; // Head matches? if (!strcmp(head->name, name)) { // Delete head temp = head; head = head->next; free(temp->name); free(temp); } else { Student *previous = head; Student *current = head->next; // Search list while (current != NULL) { // Check entry if (!strcmp(current->name, name)) { // Delete current temp = previous->next; previous->next = current->next; free(temp->name); free(temp); break; } // Advance pointers previous = current; current = current->next; } } } // Iterate students void iterate(iterate_function func) { Student *current = head; while (current != NULL) { // Print entry (*func)(current); current = current->next; } } // Terminate void terminate(iterate_function func) { while (head != NULL) { // Print entry Student *temp = head; head = head->next; free(temp->name); free(temp); } head = NULL; }