STU.H
#ifndef _STU_H_
#define _STU_H_
#include <myhead.h>
typedef struct{
char name[20];
float score;
int age;
char phone[15];
}stu;
typedef struct List{
union{
int len;
stu s;
};
struct List *next;
}List,*Plist;
Plist SLInit();
int SLPrint(Plist p);
int add_stu(Plist p);
int delet_stu(Plist p);
int updata_stu(Plist p);
int query_stu(Plist p);
#endif
STU.C
#include "stu.h"
Plist SLInit()
{
Plist p = malloc(sizeof(List));
if(p==NULL){
printf("申请空间失败\n");
return NULL;
}
p->len = 0;
p->next = NULL;
printf("创建单链表成功!\n");
return p;
}
//打印数据
int SLPrint(Plist p)
{
if(p ==NULL || p->len == 0){
printf("单链表不存在或者为空\n");
return -1;
}
printf("学生信息如下:\n");
Plist t = p;
for (int i = 0; i < p->len; i++){
t = t->next;
printf("姓名:%s\t年龄:%d\t成绩:%.2f\t手机号:%s\n",t->s.name,t->s.age,t->s.score,t->s.phone);
}
return 0;
}
int add_stu(Plist p){
if(p == NULL){
printf("单链表不存在!\n");
return -1;
}
Plist t = malloc(sizeof(List));
printf("请输入学生姓名:");
scanf("%s",t->s.name);
printf("请输入学生年龄:");
scanf("%d",&t->s.age);
printf("请输入学生成绩:");
scanf("%f",&t->s.score);
printf("请输入学生手机号:");
scanf("%s",t->s.phone);
t->next = p->next;
p->next = t;
p->len++;
return 0;
}
int delet_stu(Plist p){
if(p==NULL || p->len==0){
printf("单链表不存在或者为空!\n");
return -1;
}
int pos;
printf("请输入你要删除的位置:");
scanf("%d",&pos);
if( pos<1 || pos > p->len+1){
printf("位置不合法!删除失败。\n");
}else{
Plist t = p;
for(int i=0;i<pos-1;i++){
t = t->next;
}
Plist Q = t->next;
t->next = Q->next;
free(Q);
Q = NULL;
p->len--;
}
return 0;
}
int updata_stu(Plist p){
if(p==NULL || p->len==0){
printf("单链表不存在或者为空!\n");
return -1;
}
int find = -1;
float key;
printf("请输入需要修改学生信息的成绩:");
scanf("%f",&key);
Plist t = p;
for(int i=0;i<p->len;i++){
t = t->next;
if(t->s.score == key){
find = i;
break;
}
}
if(find != -1){
printf("修改后的学生年龄:");
scanf("%d",&t->s.age);
printf("修改成功!\n");
}else printf("未找到该成绩学生信息!\n");
return 0;
}
int query_stu(Plist p){
char name[20];
int find = -1;
printf("请输入需要查找学生的姓名:");
scanf("%s",name);
Plist t = p;
for(int i=0;i<p->len;i++){
t = t->next;
if(strcmp(t->s.name,name) == 0 ){
find = i;
break;
}
}
if(find != -1){
printf("%s学生信息为:\n",name);
printf("姓名:%s\t年龄:%d\t成绩:%.2f\t手机号:%s\n",
t->s.name,t->s.age,
t->s.score,t->s.phone);
}else {
printf("查找失败!不存在%s同学。",name);
}
return 0;
}
MYMAIN.C
#include "stu.h"
int main(int argc, const char *argv[])
{
Plist p = NULL;
int choice;
while (1){
printf("------学生管理系统------\n");
printf("1. 创建学生单链表\n");
printf("2. 添加学生信息\n");
printf("3. 删除学生信息\n");
printf("4. 修改学生信息\n");
printf("5. 查询学生信息\n");
printf("6. 显示学生信息\n");
printf("7. 退出\n");
printf("请输入你的选择: ");
scanf("%d", &choice);
switch (choice){
case 1:p = SLInit();break;
case 2:add_stu(p);break;
case 3:delet_stu(p);break;
case 4:updata_stu(p);break;
case 5:query_stu(p);break;
case 6:SLPrint(p);break;
case 7: return 0;
default : printf("输入错误!");break;
}
}
return 0;
}