#include #include #include #define MAX_STR 32 typedef struct { char name[MAX_STR]; char major[MAX_STR]; } StudentType; typedef struct Node { StudentType *data; struct Node *next; } NodeType; void createStudent(char*, char*, StudentType**); void createNode(NodeType**, StudentType*); void printStudent(StudentType*); void freeList(NodeType*); int main() { NodeType *ourClassroom = NULL; NodeType *currNode = 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); createNode(&currNode, currStudent); currNode->next = ourClassroom; ourClassroom = currNode; } printf("\nHere is the list:\n"); printf("%-15s %-15s\n", "NAME", "MAJOR"); printf("--------------- ---------------\n"); currNode = ourClassroom; while(currNode != NULL) { printStudent(currNode->data); currNode = currNode->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); } // Allocates memory for a new list Node void createNode(NodeType **node, StudentType *data) { *node = (NodeType *) malloc(sizeof(NodeType)); if (node == NULL) { printf("Memory allocation error\n"); exit(0); } (*node)->data = data; (*node)->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(NodeType *aNode) { NodeType *nextItem; while(aNode != NULL) { nextItem = aNode->next; free(aNode->data); free(aNode); aNode = nextItem; } }