| 帮我编写一个C语言动态链表代码,用于学生成绩管理系统,功能有在特定位置插入,添加,删除,输出,查找,按成绩大晓小输出等功能
时间: 2023-04-10 07:04:28 浏览: 139
好的,以下是一个简单的C语言动态链表代码,用于学生成绩管理系统:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct student {
char name[20];
int score;
struct student *next;
} Student;
Student *create() {
Student *head = (Student *)malloc(sizeof(Student));
head->next = NULL;
return head;
}
void insert(Student *head, int pos, char *name, int score) {
Student *p = head;
int i = 0;
while (p && i < pos - 1) {
p = p->next;
i++;
}
if (!p || i > pos - 1) {
printf("插入位置不合法\n");
return;
}
Student *new_node = (Student *)malloc(sizeof(Student));
strcpy(new_node->name, name);
new_node->score = score;
new_node->next = p->next;
p->next = new_node;
}
void add(Student *head, char *name, int score) {
Student *p = head;
while (p->next) {
p = p->next;
}
Student *new_node = (Student *)malloc(sizeof(Student));
strcpy(new_node->name, name);
new_node->score = score;
new_node->next = NULL;
p->next = new_node;
}
void del(Student *head, int pos) {
Student *p = head;
int i = 0;
while (p->next && i < pos - 1) {
p = p->next;
i++;
}
if (!p->next || i > pos - 1) {
printf("删除位置不合法\n");
return;
}
Student *del_node = p->next;
p->next = del_node->next;
free(del_node);
}
void output(Student *head) {
Student *p = head->next;
while (p) {
printf("%s %d\n", p->name, p->score);
p = p->next;
}
}
void search(Student *head, int score) {
Student *p = head->next;
while (p) {
if (p->score == score) {
printf("%s %d\n", p->name, p->score);
}
p = p->next;
}
}
void sort(Student *head) {
int len = 0;
Student *p = head->next;
while (p) {
len++;
p = p->next;
}
for (int i = 0; i < len - 1; i++) {
p = head->next;
for (int j = 0; j < len - i - 1; j++) {
if (p->score > p->next->score) {
int temp_score = p->score;
p->score = p->next->score;
p->next->score = temp_score;
char temp_name[20];
strcpy(temp_name, p->name);
strcpy(p->name, p->next->name);
strcpy(p->next->name, temp_name);
}
p = p->next;
}
}
}
int main() {
Student *head = create();
int choice, pos, score;
char name[20];
while (1) {
printf("1.插入 2.添加 3.删除 4.输出 5.查找 6.排序 7.退出\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("请输入插入位置和学生姓名、成绩:\n");
scanf("%d %s %d", &pos, name, &score);
insert(head, pos, name, score);
break;
case 2:
printf("请输入学生姓名、成绩:\n");
scanf("%s %d", name, &score);
add(head, name, score);
break;
case 3:
printf("请输入删除位置:\n");
scanf("%d", &pos);
del(head, pos);
break;
case 4:
output(head);
break;
case 5:
printf("请输入查找成绩:\n");
scanf("%d", &score);
search(head, score);
break;
case 6:
sort(head);
output(head);
break;
case 7:
exit(0);
default:
printf("输入错误,请重新输入\n");
break;
}
}
return 0;
}
```
这个代码实现了在特定位置插入、添加、删除、输出、查找、按成绩大小排序等功能。
阅读全文