Data_Structure/作業/unit4/Student.c

110 lines
2.5 KiB
C
Raw Permalink Normal View History

2025-01-20 21:30:53 +08:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 24
// <20>w<EFBFBD>q<EFBFBD>ǥ͸`<60>I<EFBFBD><49><EFBFBD>c
typedef struct StudentNode {
char name[MAX_NAME_LENGTH];
int english;
int math;
struct StudentNode* prev;
struct StudentNode* next;
} StudentNode;
// <20>w<EFBFBD>q<EFBFBD><71><EFBFBD>V<EFBFBD><EFBFBD><ECB5B2><EFBFBD>C<EFBFBD><43><EFBFBD>c
typedef struct {
StudentNode* head;
StudentNode* tail;
} StudentList;
// <20><><EFBFBD>l<EFBFBD>ƾǥͦC<CDA6><43>
void initList(StudentList* list) {
list->head = NULL;
list->tail = NULL;
}
// <20>b<EFBFBD><62><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>J<EFBFBD>s<EFBFBD>ǥ͸`<60>I
void insertStudent(StudentList* list, char* name, int english, int math) {
int i=0;
StudentNode* newNode = (StudentNode*)malloc(sizeof(StudentNode));
while(name[i]!='\0'){
newNode->name[i] = name[i];
// printf("%c",name[i]);
i++;
}
newNode->name[i] = '\0';
newNode->english = english;
newNode->math = math;
newNode->next = NULL;
if (list->tail == NULL) {
newNode->prev = NULL;
list->head = newNode;
list->tail = newNode;
} else {
newNode->prev = list->tail;
list->tail->next = newNode;
list->tail = newNode;
}
}
// <20>q<EFBFBD><71><EFBFBD><EFBFBD>Ū<EFBFBD><C5AA><EFBFBD>ǥ͸<C7A5><CDB8><EFBFBD>
void readStudentsFromFile(StudentList* list, const char* filename) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("<EFBFBD>L<EFBFBD>k<EFBFBD>}<7D><><EFBFBD>ɮ<EFBFBD> %s\n", filename);
return;
}
char line[100];
int lineCount = 0;
// <20><><EFBFBD>L<EFBFBD>e<EFBFBD>|<7C><>
// <20><><EFBFBD>|<7C><>
while (lineCount < 4 && fgets(line, sizeof(line), file)) {
lineCount++;
}
// Ū<><C5AA><EFBFBD>ǥ͸<C7A5><CDB8><EFBFBD>
char name[MAX_NAME_LENGTH];
int english, math;
while (fscanf(file, "%49[^\t]\t%d\t%d\n", name, &english, &math) == 3) {
insertStudent(list, name, english, math);
}
fclose(file);
}
// <20>C<EFBFBD>L<EFBFBD>ǥͦC<CDA6><43>
void printStudentList(StudentList* list) {
StudentNode* current_head = list->head;
StudentNode* current_tail = list->tail;
printf("<EFBFBD>m<EFBFBD>W\t\t<EFBFBD>^<5E><>\t<EFBFBD>ƾ<EFBFBD>\n");
printf("<EFBFBD>q<EFBFBD>Y<EFBFBD>}<7D>l\n");
printf("--------------------------------\n");
while (current_head != NULL) {
printf("%-15s\t%d\t%d\n", current_head->name, current_head->english, current_head->math);
current_head = current_head->next;
}
printf("\n<EFBFBD>q<EFBFBD><EFBFBD><EFBFBD>}<7D>l\n");
printf("--------------------------------\n");
while (current_tail != NULL) {
printf("%-15s\t%d\t%d\n", current_tail->name, current_tail->english, current_tail->math);
current_tail = current_tail->prev;
}
}
int main() {
StudentList list;
initList(&list);
readStudentsFromFile(&list, "YunTechStudents.txt");
printStudentList(&list);
return 0;
}