graph TD
A[开始] --> B[显示主菜单]
B --> C{选择操作}
C -->|1| D[创建链表]
C -->|2| E[查找学生]
C -->|3| F[插入学生]
C -->|4| G[删除学生]
C -->|5| H[打印链表]
C -->|6| I[退出程序]
D --> B
E --> B
F --> B
G --> B
H --> B
I --> J[释放内存]
J --> K[结束]
2. 核心代码实现
2.1 链表创建函数
stud *creat(void) {
stud *p, *h, *s;
int i, n;
printf("\nPlease input the number of students: ");
scanf("%d", &n);
clear_input_buffer(); // 清空输入缓冲区if(n <= 0) {
printf("Invalid number of students!\n");
returnNULL;
}
/* 创建头节点 */
h = (stud *)malloc(sizeof(stud));
if(h == NULL) {
printf("Cannot allocate memory!\n");
exit(1);
}
strcpy(h->name, "HEAD");
h->link = NULL;
p = h;
for(i = 0; i < n; i++) {
s = (stud *)malloc(sizeof(stud));
if(s == NULL) {
printf("Cannot allocate memory!\n");
exit(1);
}
printf("Please input student %d's name: ", i+1);
fgets(s->name, MAX_NAME_LEN, stdin);
s->name[strcspn(s->name, "\n")] = '\0'; // 去除换行符
s->link = NULL;
p->link = s;
p = s;
}
return h;
}
============================================
Student Linked List Management System
============================================
[1] Create linked list
[2] Search student
[3] Insert student (at head)
[4] Delete student
[5] Print all students
[6] Exit program
============================================
Note: Create list first if not exist
============================================
Please input your choice (1-6):
创建链表:
Please input the number of students:3
Please input student 1's name: Alice
Please input student 2's name: Bob
Please input student 3's name: Charlie
Linked list created successfully!
打印链表:
Current student list:
=====================1. Alice
2. Bob
3. Charlie
=====================
Total: 3 student(s)
插入学生:
Please input the student's name: David
Student inserted successfully!
Current student list:
=====================1. David
2. Alice
3. Bob
4. Charlie
=====================
Total: 4 student(s)
删除学生:
Input the student's name to delete: Bob
Student 'Bob' deleted successfully!
Current student list:
=====================1. David
2. Alice
3. Charlie
=====================
Total: 3 student(s)
7. 总结
7.1 心得体会
通过本次学生链表管理系统的设计与实现,我深刻理解了链表数据结构的基本原理和操作方式。从最初的代码调试到最终的功能完善,整个过程让我对 C 语言的指针操作、内存管理有了更深入的认识。特别是动态内存分配和释放,让我意识到程序健壮性的重要性。