学生信息管理系统c语言单链表代码
时间: 2023-11-05 09:39:07 浏览: 48
以下是一个简单的学生信息管理系统的C语言单链表代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student {
char name[20];
int id;
float score;
struct student *next;
};
struct student *create_student(char name[], int id, float score) {
struct student *s = (struct student *) malloc(sizeof(struct student));
strcpy(s->name, name);
s->id = id;
s->score = score;
s->next = NULL;
return s;
}
void append_student(struct student **head, struct student *s) {
if (*head == NULL) {
*head = s;
} else {
struct student *p = *head;
while (p->next != NULL) {
p = p->next;
}
p->next = s;
}
}
void print_student(struct student *s) {
printf("Name: %s\nID: %d\nScore: %.2f\n", s->name, s->id, s->score);
}
void print_all_students(struct student *head) {
struct student *p = head;
while (p != NULL) {
print_student(p);
p = p->next;
}
}
void delete_student(struct student **head, int id) {
struct student *p = *head;
struct student *prev = NULL;
while (p != NULL) {
if (p->id == id) {
if (prev == NULL) {
*head = p->next;
} else {
prev->next = p->next;
}
free(p);
return;
}
prev = p;
p = p->next;
}
}
int main() {
struct student *head = NULL;
append_student(&head, create_student("Alice", 1001, 89.5));
append_student(&head, create_student("Bob", 1002, 78.0));
append_student(&head, create_student("Charlie", 1003, 92.5));
print_all_students(head);
delete_student(&head, 1002);
printf("\nAfter deleting student with ID 1002:\n");
print_all_students(head);
return 0;
}