用c语言链表设计一个学生选课系统
时间: 2023-05-20 22:05:43 浏览: 200
好的,以下是一个用C语言链表设计的学生选课系统的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct course {
char name[20];
int id;
int capacity;
int enrolled;
struct course *next;
} Course;
typedef struct student {
char name[20];
int id;
Course *courses;
struct student *next;
} Student;
Course *create_course(char name[], int id, int capacity) {
Course *new_course = (Course*) malloc(sizeof(Course));
strcpy(new_course->name, name);
new_course->id = id;
new_course->capacity = capacity;
new_course->enrolled = 0;
new_course->next = NULL;
return new_course;
}
Student *create_student(char name[], int id) {
Student *new_student = (Student*) malloc(sizeof(Student));
strcpy(new_student->name, name);
new_student->id = id;
new_student->courses = NULL;
new_student->next = NULL;
return new_student;
}
void add_course(Student *student, Course *course) {
if (course->enrolled < course->capacity) {
Course *temp = student->courses;
while (temp != NULL) {
if (temp->id == course->id) {
printf("Student %s has already enrolled in course %s.\n", student->name, course->name);
return;
}
temp = temp->next;
}
course->enrolled++;
Course *new_course = create_course(course->name, course->id, course->capacity);
new_course->next = student->courses;
student->courses = new_course;
printf("Student %s has successfully enrolled in course %s.\n", student->name, course->name);
} else {
printf("Course %s is already full.\n", course->name);
}
}
void print_courses(Course *courses) {
printf("Course ID\tCourse Name\tCapacity\tEnrolled\n");
while (courses != NULL) {
printf("%d\t\t%s\t\t%d\t\t%d\n", courses->id, courses->name, courses->capacity, courses->enrolled);
courses = courses->next;
}
}
void print_students(Student *students) {
printf("Student ID\tStudent Name\tEnrolled Courses\n");
while (students != NULL) {
printf("%d\t\t%s\t\t", students->id, students->name);
Course *courses = students->courses;
while (courses != NULL) {
printf("%s ", courses->name);
courses = courses->next;
}
printf("\n");
students = students->next;
}
}
int main() {
Course *c1 = create_course("Math", 1, 3);
Course *c2 = create_course("Science", 2, 2);
Course *c3 = create_course("History", 3, 1);
Student *s1 = create_student("Alice", 1001);
Student *s2 = create_student("Bob", 1002);
Student *s3 = create_student("Charlie", 1003);
add_course(s1, c1);
add_course(s1, c2);
add_course(s1, c3);
add_course(s2, c1);
add_course(s2, c2);
add_course(s3, c1);
print_courses(c1);
print_courses(c2);
print_courses(c3);
print_students(s1);
print_students(s2);
print_students(s3);
return 0;
}
```
这个程序使用了两个结构体,一个是Course,表示课程,另一个是Student,表示学生。每个课程有一个ID、名称、容量和已选人数,每个学生有一个ID、名称和已选课程列表。我们可以使用add_course函数将学生添加到课程中,如果课程已满或学生已经在课程中,则会输出相应的错误信息。最后,我们可以使用print_courses和print_students函数分别打印所有课程和学生的信息。
希望这个示例代码能够帮助你理解如何使用链表设计一个学生选课系统。
阅读全文