1. 定義鏈表節(jié)點(diǎn)結(jié)構(gòu):首先定義一個(gè)結(jié)構(gòu)體來表示鏈表中的每個(gè)節(jié)點(diǎn),通常包含學(xué)生的基本信息和成績。
```c
typedef struct Student {
int id; // 學(xué)生ID
char name[50]; // 學(xué)生姓名
float score; // 成績
struct Student next; // 指向下一個(gè)節(jié)點(diǎn)的指針
} Student;
```
2. 初始化鏈表:創(chuàng)建一個(gè)函數(shù)來初始化鏈表,通常設(shè)置一個(gè)頭節(jié)點(diǎn)(哨兵節(jié)點(diǎn))。
```c
Student initList() {
Student head = (Student )malloc(sizeof(Student));
head->next = NULL;
return head;
}
```
3. 添加成績:創(chuàng)建一個(gè)函數(shù)來添加新的學(xué)生成績到鏈表末尾。
```c
void addScore(Student head, int id, c*t char name, float score) {
Student newStudent = (Student )malloc(sizeof(Student));
newStudent->id = id;
strcpy(newStudent->name, name);
newStudent->score = score;
newStudent->next = NULL;
Student current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newStudent;
}
```
4. 刪除成績:創(chuàng)建一個(gè)函數(shù)來根據(jù)學(xué)生ID刪除對應(yīng)的成績節(jié)點(diǎn)。
```c
void deleteScore(Student head, int id) {
Student current = head;
Student prev = NULL;
while (current != NULL && current->id != id) {
prev = current;
current = current->next;
}
if (current == NULL) {
printf("Student not found.\n");
} else {
if (prev == NULL) {
// 刪除頭節(jié)點(diǎn)
head = current->next;
} else {
prev->next = current->next;
}
free(current);
}
}
```
5. 查找成績:創(chuàng)建一個(gè)函數(shù)來根據(jù)學(xué)生ID查找成績。
```c
Student findScore(Student head, int id) {
Student current = head->next; // 跳過哨兵節(jié)點(diǎn)
while (current != NULL) {
if (current->id == id) {
return current;
}
current = current->next;
}
return NULL; // 未找到
}
```
6. 打印鏈表:創(chuàng)建一個(gè)函數(shù)來遍歷鏈表并打印所有學(xué)生的成績信息。
```c
void printList(Student head) {
Student current = head->next; // 跳過哨兵節(jié)點(diǎn)
while (current != NULL) {
printf("ID: %d, Name: %s, Score: %.2f\n", current->id, current->name, current->score);
current = current->next;
}
}
```
7. 釋放鏈表內(nèi)存:創(chuàng)建一個(gè)函數(shù)來釋放鏈表占用的所有內(nèi)存。
```c
void freeList(Student head) {
Student current = head->next;
while (current != NULL) {
Student temp = current;
current = current->next;
free(temp);
}
free(head); // 釋放頭節(jié)點(diǎn)
}
```
這些基本操作提供了學(xué)生成績管理系統(tǒng)的框架。你可以根據(jù)自己的需求添加更多的功能,如更新成績、排序顯示等。記得在編寫代碼時(shí),要考慮到邊界條件和內(nèi)存管理,以避免潛在的錯(cuò)誤和內(nèi)存泄漏。