以下是使用C语言实现学生信息管理系统的示例代码,并利用链表数据结构存储学生信息:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 定义学生结构体
typedef struct student {
    int id;
    char name[20];
    int age;
    struct student* next;
} Student;

// 初始化链表
Student* initList() {
    Student* head = (Student*)malloc(sizeof(Student));
    head->next = NULL;
    return head;
}

// 添加学生信息
void addStudent(Student* head, int id, char* name, int age) {
    Student* newStudent = (Student*)malloc(sizeof(Student));
    newStudent->id = id;
    strcpy(newStudent->name, name);
    newStudent->age = age;

    newStudent->next = head->next;
    head->next = newStudent;
}

// 删除学生信息
void deleteStudent(Student* head, int id) {
    Student* p = head->next;
    Student* pre = head;

    while (p != NULL) {
        if (p->id == id) {
            pre->next = p->next;
            free(p);
            return;
        }
        pre = p;
        p = p->next;
    }

    printf('Student with ID %d not found.\n', id);
}

// 查找学生信息
void findStudent(Student* head, int id) {
    Student* p = head->next;

    while (p != NULL) {
        if (p->id == id) {
            printf('ID: %d, Name: %s, Age: %d\n', p->id, p->name, p->age);
            return;
        }
        p = p->next;
    }

    printf('Student with ID %d not found.\n', id);
}

// 显示所有学生信息
void displayStudents(Student* head) {
    Student* p = head->next;

    while (p != NULL) {
        printf('ID: %d, Name: %s, Age: %d\n', p->id, p->name, p->age);
        p = p->next;
    }
}

// 释放链表内存
void freeList(Student* head) {
    Student* p = head;
    while (p != NULL) {
        Student* temp = p->next;
        free(p);
        p = temp;
    }
}

int main() {
    Student* head = initList();

    addStudent(head, 1, 'Alice', 20);
    addStudent(head, 2, 'Bob', 21);
    addStudent(head, 3, 'Charlie', 22);

    printf('All students:\n');
    displayStudents(head);

    printf('\nDelete student with ID 2.\n');
    deleteStudent(head, 2);

    printf('\nAll students after deletion:\n');
    displayStudents(head);

    printf('\nFind student with ID 3.\n');
    findStudent(head, 3);

    freeList(head);

    return 0;
}

运行上述代码,将输出以下结果:

All students:
ID: 3, Name: Charlie, Age: 22
ID: 2, Name: Bob, Age: 21
ID: 1, Name: Alice, Age: 20

Delete student with ID 2.

All students after deletion:
ID: 3, Name: Charlie, Age: 22
ID: 1, Name: Alice, Age: 20

Find student with ID 3.
ID: 3, Name: Charlie, Age: 22

原文地址: https://www.cveoy.top/t/topic/pipG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录