How to use linked lists in C language to write student information

You can store and manage student information using a linked list by following these steps:

  1. Define a struct for student information, which includes fields for student ID, name, and age.
typedef struct {
    int id;
    char name[20];
    int age;
} Student;
  1. Define a structure for linked list nodes that includes student information and a pointer to the next node.
typedef struct Node {
    Student student;
    struct Node *next;
} Node;
  1. Define the pointers to the head and tail nodes of the linked list, and initialize them to NULL.
Node *head = NULL;
Node *tail = NULL;
  1. Implement a function to add student information, inserting the new student information as a node at the end of the linked list.
void addStudent(Student student) {
    Node *newNode = (Node *)malloc(sizeof(Node));
    newNode->student = student;
    newNode->next = NULL;

    if (head == NULL) {
        head = newNode;
        tail = newNode;
    } else {
        tail->next = newNode;
        tail = newNode;
    }
}
  1. Create a function to traverse the linked list and print all student information.
void printStudents() {
    Node *node = head;
    while (node != NULL) {
        printf("学号:%d, 姓名:%s, 年龄:%d\n", node->student.id, node->student.name, node->student.age);
        node = node->next;
    }
}
  1. Additional functions can be implemented as needed, such as deleting student information or searching for student information.

By following the above steps, it is possible to use a linked list to store and manage student information.

bannerAds