運用結構體 + 鏈結串列實作動態學生資料管理:新增、查詢、修改、刪除。因學生人數不定,陣列固定大小不夠彈性,鏈結串列是經典解法。
typedef struct Student {
char no[4]; // 學號 (3 碼)
char name[10]; // 姓名
int chinese; // 國文
int math; // 數學
int english; // 英文
struct Student *next; // 指向下一筆
} StudentList;
init()void init(StudentList *&stuList) {
stuList = (StudentList *)malloc(sizeof(StudentList));
stuList->next = NULL; // 空串列
}
insert() — 尾插法void insert(StudentList *&stuList) {
StudentList *p = stuList, *s;
while (p->next != NULL) p = p->next; // 找尾節點
do {
s = (StudentList *)malloc(sizeof(StudentList));
puts("please insert student data(NO,Name,Chinese,Math,English):");
scanf("%3s%10s", &s->no, &s->name);
scanf("%d%d%d", &s->chinese, &s->math, &s->english);
// 簡易驗證:分數 0-100
if (s->chinese < 0 || s->chinese > 100 || ...) { puts("input data error !!!"); return; }
s->next = NULL;
p->next = s; p = p->next; // 掛上新節點,移動尾標
fflush(stdin);
puts("Continue? ENTER to yes or input no to exit");
} while (getchar() == '\n');
}
select() — 遍歷列印void select(StudentList *stuList) {
StudentList *p = stuList->next;
if (!p) { puts("there is no data,please insert!!"); getchar(); return; }
puts("No\tName\tChinese\tMath\tEnglish");
while (p) { printf("%s\t%s\t%d\t%d\t%d\n", p->no, p->name, p->chinese, p->math, p->english); p = p->next; }
getchar();
}
update() — 依學號搜尋後覆寫void update(StudentList *&stuList) {
StudentList *p = stuList->next;
char no[4]; gets(no);
while (p && strcmp(p->no, no)) p = p->next; // 找節點
if (!p) { puts("can't find this student's record!!!"); getchar(); return; }
// 顯示舊資料後輸入新資料 (不含學號)
puts("please update student data(Name,Chinese,Math,English):");
scanf("%10s", &p->name); scanf("%d%d%d", &p->chinese, &p->math, &p->english);
puts("update successful");
}
deleteData() — 經典前驅節點法void deleteData(StudentList *stuList) {
StudentList *p = stuList, *q; // p 指向前驅
char no[4]; gets(no);
while (p->next && strcmp(p->next->no, no)) p = p->next;
if (!p->next) { puts("can't find..."); getchar(); return; }
puts("Are you sure delete? press ENTER to confirm");
if (getchar() == '\n') {
q = p->next; p->next = q->next; free(q); // 斷鏈 + 釋放
puts("delete successful");
}
getchar();
}
void studentScoreManege() {
StudentList *stuList = NULL; int oprate;
init(stuList);
do {
system("cls"); // 清屏
puts("1. select 2. insert 3. update 4. delete 0. exit");
scanf("%d", &oprate);
switch (oprate) {
case 1: select(stuList); break;
case 2: insert(stuList); break;
case 3: update(stuList); break;
case 4: deleteData(stuList); break;
}
} while (oprate != 0);
}
char no[4]),輸入超長會緩衝區溢位 → 改用動態配置或 fgets + 長度檢查save/load 至二進位/文字檔system("cls")、fflush(stdin) 非標準 C,跨平台需替換這是典型的「資料結構 + 標準 I/O + 選單驅動」綜合練習。完整打通後,你將掌握:動態記憶體管理、指標多重間接存取、鏈結串列四大操作 (增刪改查)、使用者互動流程控制。建議以此為基礎,逐步加入上述改進,演化成完整的專案作品集。