Data_Structure/作業/unit4/Student.c
2025-01-20 21:30:53 +08:00

110 lines
2.5 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 24
// 定義學生節點結構
typedef struct StudentNode {
char name[MAX_NAME_LENGTH];
int english;
int math;
struct StudentNode* prev;
struct StudentNode* next;
} StudentNode;
// 定義雙向鏈結串列結構
typedef struct {
StudentNode* head;
StudentNode* tail;
} StudentList;
// 初始化學生列表
void initList(StudentList* list) {
list->head = NULL;
list->tail = NULL;
}
// 在尾部插入新學生節點
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;
}
}
// 從文件讀取學生資料
void readStudentsFromFile(StudentList* list, const char* filename) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("無法開啟檔案 %s\n", filename);
return;
}
char line[100];
int lineCount = 0;
// 跳過前四行
// 把四行
while (lineCount < 4 && fgets(line, sizeof(line), file)) {
lineCount++;
}
// 讀取學生資料
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);
}
// 列印學生列表
void printStudentList(StudentList* list) {
StudentNode* current_head = list->head;
StudentNode* current_tail = list->tail;
printf("姓名\t\t英文\t數學\n");
printf("從頭開始\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從尾開始\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;
}