C语言学生选课系统链表实现
时间: 2023-09-02 17:14:13 浏览: 116
以下是一个简单的 C 语言学生选课系统链表实现:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct course {
char name[20];
int credit;
struct course *next;
};
struct student {
char name[20];
struct course *courses;
struct student *next;
};
struct student *head = NULL;
void add_student() {
struct student *new_student = (struct student *) malloc(sizeof(struct student));
printf("Enter student name: ");
scanf("%s", new_student->name);
new_student->courses = NULL;
new_student->next = NULL;
if (head == NULL) {
head = new_student;
} else {
struct student *cur = head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = new_student;
}
}
void add_course() {
printf("Enter student name: ");
char name[20];
scanf("%s", name);
struct student *cur = head;
while (cur != NULL) {
if (strcmp(cur->name, name) == 0) {
struct course *new_course = (struct course *) malloc(sizeof(struct course));
printf("Enter course name: ");
scanf("%s", new_course->name);
printf("Enter course credit: ");
scanf("%d", &new_course->credit);
new_course->next = NULL;
if (cur->courses == NULL) {
cur->courses = new_course;
} else {
struct course *cur_course = cur->courses;
while (cur_course->next != NULL) {
cur_course = cur_course->next;
}
cur_course->next = new_course;
}
return;
}
cur = cur->next;
}
printf("Student not found.\n");
}
void print_report() {
struct student *cur = head;
while (cur != NULL) {
printf("Student name: %s\n", cur->name);
struct course *cur_course = cur->courses;
while (cur_course != NULL) {
printf("Course name: %s, Course credit: %d\n", cur_course->name, cur_course->credit);
cur_course = cur_course->next;
}
printf("------------------------------\n");
cur = cur->next;
}
}
int main() {
int choice;
do {
printf("1. Add student\n");
printf("2. Add course\n");
printf("3. Print report\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_student();
break;
case 2:
add_course();
break;
case 3:
print_report();
break;
case 4:
exit(0);
break;
default:
printf("Invalid choice.\n");
}
} while (1);
return 0;
}
```
这个程序使用两个结构体来实现学生选课系统。一个结构体用于表示课程,另一个结构体用于表示学生。每个学生都有一个指向他们所选课程的指针。这个程序使用链表来存储学生和课程信息。
在 `add_student` 函数中,新建一个学生节点并从用户输入中获取学生姓名。如果链表为空,则将新节点设置为链表头。否则,遍历链表并将新节点插入到链表末尾。
在 `add_course` 函数中,从用户输入中获取学生姓名。然后遍历链表以查找该学生。如果找到了该学生,则新建一个课程节点并从用户输入中获取课程名称和学分。如果该学生没有选过课,则将新节点设置为该学生的课程列表的头。否则,遍历学生的课程列表并将新节点插入到列表末尾。
在 `print_report` 函数中,遍历链表并打印每个学生的姓名和所选课程的名称和学分。
阅读全文
相关推荐
















