创建一个链表来注册 C 学生

标签 c linked-list

在parser.h中:

typedef enum _SEX {MALE = 'M', FEMALE = 'F', OTHER = 'O'} SEX;

struct course {
 char grade;
 unsigned int number;
 struct course *next;
};

struct student {
  char name[MAX_NAME_LEN];
  unsigned int age;
  SEX sex;
  float gpa;
  struct course *courses;
  struct student *next;
 };

在parser.c中: 我有一个函数 struct Student * enroll_student(...) 我无法更改。此函数创建一个新学生并将其存储在列表中适当的位置(遵循字典顺序)。这就是我到目前为止所拥有的...... 我的问题:我不知道如何访问枚举 SEX,也不知道这是否是正确的方法。 任何反馈或帮助将不胜感激。谢谢你!

   /*globally declared*/
   static struct student *head; 

struct student* enroll_student(char *name, unsigned int age, SEX sex, float gpa){

 struct student *enroll = NULL;
   /*allocate memory*/
    enroll = (struct student*)malloc(sizeof(struct));

  if(enroll != NULL){
    /*INITIALIZE*/
    strncpy(enroll->name, name, MAX_NAME_LEN);
    enroll->age = age; 
    /* How do I access the ENUM SEX?*/
    enroll->gpa = gpa; 
    enroll->next = NULL;

   }
   return enroll;

}

最佳答案

enroll_student 函数用于在链接列表中插入任何内容。该函数的目的是 a) 创建一个新的学生对象并 b) 初始化该对象。因此,当您想要一个新的学生对象时,您可以调用该函数,但必须在该函数外部添加用于在链接列表中插入学生对象的代码。像这样的东西:

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

#define MAX_NAME_LEN 100

typedef enum _SEX {MALE = 'M', FEMALE = 'F', OTHER = 'O'} SEX;

struct course {
  char grade;
  unsigned int number;
  struct course *next;
};

struct student {
  char name[MAX_NAME_LEN];
  unsigned int age;
  SEX sex;
  float gpa;
  struct course *courses;
  struct student *next;
};

struct student* enroll_student(char *name, unsigned int age, SEX sex, float gpa){
  struct student *enroll = NULL;
  /*allocate memory*/
  enroll = malloc(sizeof *enroll);

  if(enroll != NULL){
    /*INITIALIZE*/
    strncpy(enroll->name, name, MAX_NAME_LEN);
    enroll->age = age;
    enroll->sex = sex;
    enroll->gpa = gpa;
    enroll->courses = NULL;
    enroll->next = NULL;

  }
  return enroll;
}

int main(void) {
  static struct student *head = NULL;
  struct student* st;

  // Make a new student
  st = enroll_student("Bart", 21, MALE, 1.0);

  // Insert in front of list
  st->next = head;
  head = st;

  // Make a new student
  st = enroll_student("Kim", 25, FEMALE, 1.0);

  // Insert in front of list
  st->next = head;
  head = st;

  // Print all students in the list
  struct student* tmp = head;
  while (tmp)
  {
    printf("Name: %s\n", tmp->name);
    tmp = tmp->next;
  }

  // Free allocated memory
  while (head)
  {
    tmp = head;
    head = head->next;
    free(tmp);
  }

  return 0;
}

输出:

Name: Kim
Name: Bart

关于创建一个链表来注册 C 学生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46937790/

相关文章:

c - 创建链表时不需要创建实际节点吗?

Java 读取 .txt 文件并使用子字符串进行排序

java - LinkedLists 是一种不直观的解决方案,因为大多数时候我不需要知道集合中元素的物理位置吗?

c - 文档中缺少 MSP430 重定位类型

c - 直方图,频率的计算

c++ - 将 C++ 实例方法分配给全局函数指针?

c - 如何通过进程的回溯确定传递函数参数的值?

C: 双链表中的pop函数

java - 在 Java 中创建节点类

c 的编码风格检查器(变量名,而不是缩进)