#include #include #include #define MAX_STR 32 typedef struct Student { char name[MAX_STR]; char major[MAX_STR]; struct Student *next; } StudentType; // These are the functions used in the main function. // They are defined here since the main function appears // before them. void createStudent(char*, char*, StudentType**); void printStudent(StudentType*); void freeList(StudentType*); int main() { StudentType *ourClassroom = NULL; StudentType *currStudent; char str1[MAX_STR]; char str2[MAX_STR]; printf("\nEnter student names and their majors (use -1 when done): "); while(1) { printf("\nEnter name: "); scanf("%s", str1); if (strcmp(str1, "-1") == 0) break; printf("Enter major: "); scanf("%s", str2); createStudent(str1, str2, &currStudent); currStudent->next = ourClassroom; ourClassroom = currStudent; } printf("\nHere is the list:\n"); printf("%-15s %-15s\n", "NAME","MAJOR"); printf("--------------- ---------------\n"); currStudent = ourClassroom; while(currStudent != NULL) { printStudent(currStudent); currStudent = currStudent->next; } freeList(ourClassroom); } // Allocates memory for a new student and initializes it with the given data void createStudent(char *name, char *major, StudentType **student) { *student = (StudentType *) malloc(sizeof(StudentType)); if (student == NULL) { printf("Memory allocation error\n"); exit(0); } strcpy((*student)->name, name); strcpy((*student)->major, major); (*student)->next = NULL; } // Prints a single student's information void printStudent(StudentType *sPtr) { printf("%-15s %-15s\n", sPtr->name, sPtr->major); } // Free all items in a Singly-Linked List void freeList(StudentType *listItem) { StudentType *nextItem; while(listItem != NULL) { nextItem = listItem->next; free(listItem); listItem = nextItem; } }