这两天结合小甲鱼老师的C视频,学习了单向链表。
之后留了一道题目,要求用所学知识作一个简陋的 学生成绩管理系统 ,具有生成、插入、删除、显示的功能。
具有基本的错误出入处理。
#include <stdio.h>
#include <stdlib.h>
struct table{
int num; //学号;
float success; //成绩;
struct table * next; //下一地址;
};
#define LEN (sizeof(struct table))
typedef struct table * TABLE;
TABLE create(); //生成
TABLE insert(TABLE head);
TABLE insertion(TABLE head, TABLE stud); //插入
TABLE del(TABLE head, int num); //删除
void print(TABLE head); //打印链表
void main(){
TABLE head;
int num;
printf("\t\t\t欢迎使用学生成绩管理系统:\n\n");
printf("请输入学生信息:\n\n");
head = create();
print(head);
printf("请输入要删除学生的学号: ");
scanf_s("%d", &num, 1);
head = del(head, num);
print(head);
printf("请输入要插入的学生信息:\n\n");
head = insert(head);
print(head);
}
//链表生成函数;
TABLE create(){
TABLE head, p1, p2;
p1 = p2 = (TABLE) malloc(LEN);
head = NULL;
do{
printf("请输入学号:");
scanf_s("%d", &p1->num, 1);
}while((p1->success < 0) || (p1->success >100));
do{
printf("请输入成绩:");
scanf_s("%f", &p1->success, 1);
}while((p1->success < 0) || (p1->success >100));
while(p1->num){
printf("\n\n");
if(!head){
head = p1;
}else{
p2->next = p1;
p2 = p1;
}
p1 = (TABLE) malloc(LEN);
do{
printf("请输入学号:");
scanf_s("%d", &p1->num, 1);
}while((p1->success < 0) || (p1->success >100));
do{
printf("请输入成绩:");
scanf_s("%f", &p1->success, 1);
}while((p1->success < 0) || (p1->success >100));
}
p2->next = NULL;
return head;
}
//插入函数(完整);
TABLE insert(TABLE head){
TABLE stud, p1;
int num = -1; //约定值 -1 不为学号;
stud = (TABLE) malloc(LEN);
do{
do{
p1 = head; //用来检测学号是否重复的链表头副本;
do{
printf("请输入学号:");
scanf_s("%d", &stud->num, 1);
}while((stud->num < 0)||(stud->num > 20000));
do{
printf("请输入成绩:");
scanf_s("%f", &stud->success, 1);
}while((stud->success < 0) || (stud->success >100));
//获取学号及成绩信息。并处理错误输入
while(p1){
if(stud->num == p1->num){
num = p1->num;
printf("\n学号重复!\n\n");
break;
}
p1 = p1->next;
}
}while(num == stud->num);
//检测链表中是否存在相同学号,是则要求重新输入。
if(!stud->num) break;
head = insertion(head, stud);
stud = (TABLE) malloc(LEN);
printf("\n");
}while(stud->num);
return head;
}
//插入函数(片段);
TABLE insertion(TABLE head, TABLE stud){
TABLE p0, p1, p2;
p1 = p2 = head;
p0 = stud;
if(!head){
p1 = p0;
p0->next = NULL;
}else{
while(p0->num > p1->num && p1->next){
p2 = p1;
p1 = p1->next;
}
if(p0->num > p1->num){ //链表尾;
p1->next = p0;
p0->next = NULL;
}else if(head == p1){ //链表头;
head = p0;
p0->next = p1;
}else{ //链表中间
p2->next = p0;
p0->next = p1;
}
}
return head;
}
//删除函数;
TABLE del(TABLE head, int num){
TABLE p1, p2;
if(!head){
printf("空表!\n\n");
}else{
p1 = p2 = head;
while(num != p1->num && p1->next){
p2 = p1;
p1 = p1->next;
}
if(num != p1->num){
printf("找不到!\n\n");
}else if(head == p1){
head = p1->next;
}else{
p2->next = p1->next;
}
}
return head;
}
//打印链表函数;
void print(TABLE head){
printf("\n\n");
while(head){
printf("学号: %d\t\t", head->num);
printf("成绩: %.1f\n\n", head->success);
head = head->next;
}
}