用c语言链表设计一个选课系统
时间: 2023-05-20 11:05:41 浏览: 140
用链表实现学生选课管理系统
5星 · 资源好评率100%
好的,以下是用 C 语言链表设计一个选课系统的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 20
typedef struct course {
char name[MAX_NAME_LEN];
int id;
int capacity;
int enrolled;
struct course *next;
} Course;
Course *head = NULL;
void add_course(char *name, int id, int capacity) {
Course *new_course = (Course *)malloc(sizeof(Course));
strncpy(new_course->name, name, MAX_NAME_LEN);
new_course->id = id;
new_course->capacity = capacity;
new_course->enrolled = 0;
new_course->next = NULL;
if (head == NULL) {
head = new_course;
} else {
Course *cur = head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = new_course;
}
}
void enroll(int id) {
Course *cur = head;
while (cur != NULL) {
if (cur->id == id) {
if (cur->enrolled < cur->capacity) {
cur->enrolled++;
printf("Enrolled in %s\n", cur->name);
} else {
printf("Course %s is full\n", cur->name);
}
return;
}
cur = cur->next;
}
printf("Course not found\n");
}
void print_courses() {
Course *cur = head;
while (cur != NULL) {
printf("%d: %s (%d/%d)\n", cur->id, cur->name, cur->enrolled, cur->capacity);
cur = cur->next;
}
}
int main() {
add_course("Math", 1, 30);
add_course("English", 2, 20);
add_course("History", 3, 25);
enroll(1);
enroll(1);
enroll(1);
enroll(1);
enroll(1);
enroll(1);
enroll(1);
enroll(1);
enroll(1);
enroll(1);
enroll(1);
enroll(1);
enroll(1);
enroll(1);
enroll(1);
enroll(1);
enroll(2);
enroll(2);
enroll(2);
enroll(2);
enroll(2);
enroll(2);
enroll(2);
enroll(2);
enroll(2);
enroll(2);
enroll(2);
enroll(3);
enroll(3);
enroll(3);
enroll(3);
enroll(3);
enroll(3);
enroll(3);
enroll(3);
enroll(3);
enroll(3);
enroll(3);
enroll(3);
enroll(3);
enroll(3);
print_courses();
return 0;
}
```
这个选课系统使用链表来存储课程信息,每个课程包括名称、编号、容量和已选人数等信息。可以通过 `add_course` 函数添加课程,通过 `enroll` 函数选课,通过 `print_courses` 函数打印所有课程的信息。
阅读全文