用C语言链表写一个学生管理系统代码
时间: 2023-05-17 09:02:38 浏览: 68
非常感谢您的提问,以下是一个用C语言链表写的学生管理系统代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student {
int id;
char name[20];
int score;
struct student *next;
} Student;
Student *create_student(int id, char *name, int score) {
Student *s = (Student *)malloc(sizeof(Student));
s->id = id;
strcpy(s->name, name);
s->score = score;
s->next = NULL;
return s;
}
void add_student(Student **head, Student *s) {
if (*head == NULL) {
*head = s;
} else {
Student *p = *head;
while (p->next != NULL) {
p = p->next;
}
p->next = s;
}
}
void print_student(Student *s) {
printf("id: %d, name: %s, score: %d\n", s->id, s->name, s->score);
}
void print_all_students(Student *head) {
Student *p = head;
while (p != NULL) {
print_student(p);
p = p->next;
}
}
void delete_student(Student **head, int id) {
if (*head == NULL) {
return;
}
if ((*head)->id == id) {
Student *p = *head;
*head = (*head)->next;
free(p);
} else {
Student *p = *head;
while (p->next != NULL && p->next->id != id) {
p = p->next;
}
if (p->next != NULL) {
Student *q = p->next;
p->next = q->next;
free(q);
}
}
}
int main() {
Student *head = NULL;
add_student(&head, create_student(1, "Tom", 80));
add_student(&head, create_student(2, "Jerry", 90));
add_student(&head, create_student(3, "Alice", 85));
add_student(&head, create_student(4, "Bob", 95));
print_all_students(head);
delete_student(&head, 3);
print_all_students(head);
return 0;
}