389 字
2 分钟
链表练习--简易模拟学籍管理
#include <stdio.h>#include <stdlib.h>#include <string.h>typedef struct stu{ int num; char name[21]; struct stu *next;}stu;
stu* creat(int id,char str[]);void add(stu *p,int id,char str[]);int query_value(stu *p,char name[]);stu* query_id(stu *p,int id);int del_list(stu *p,int id);void menu(stu *p);void menu_add(stu *p);void menu_edit(stu *p);
int main(){ stu *p=NULL; p=creat(0,"NULL"); menu(p); while(p!=NULL){ printf("name=%s,id=%d\n",p->name,p->num); p=p->next; }}
stu* creat(int id,char str[]){//创建链表节点 stu *new; if((new=(stu *)malloc(sizeof(stu)))==NULL){ printf("不能分配内存空间!"); exit(0); } new->num=id; strcpy(new->name,str); new->next=NULL; return new;}
void add(stu *p,int id,char str[]){//链表尾插入新节点 stu *new=NULL; new=creat(id,str); while(p->next!=NULL){ p=p->next; } p->next=new;}int query_value(stu *p,char name[]){//按照值查找节点,并返回节点序号 int i=0; while((p!=NULL)){ if (strcmp(p->name,name)==0){ return i; } p=p->next; i=i+1; } return -1;}
stu* query_id(stu *p,int id){//传入指针节点序号,并返回节点指针 if (id<0) return NULL; for (int i = 0; i < id; ++i){ if (p==NULL) return NULL; p=p->next; } return p;}
int del_list(stu *p,int id){//传入节点序号,删除节点 stu *p1,*s; if (id<1) return 0; p1=query_id(p,id-1); if (p1==NULL){//前一个节点不存在 return -1; } else{ if (p1->next==NULL){//被删除节点不存在 return 0; } else{ s=p1->next; p1->next=s->next; free(s); return 1; } }
}void menu(stu *p){ int input; printf("欢迎使用学生学籍管理系统\n"); printf("1.插入学生\n"); printf("2.修改学生\n"); printf("3.输出列表\n"); printf("请输入选项:"); if (scanf("%d",&input)!=1) return; switch(input){ case 1:{ menu_add(p); menu(p); break; } case 2:{ menu_edit(p); menu(p); break; } case 3:break; }}void menu_add(stu *p){ int id; char name[21]; printf("请输入要添加的姓名:\n"); if (scanf("%20s",name)!=1) return; printf("请输入学号:\n"); if (scanf("%d",&id)!=1) return; add(p,id,name);}
void menu_edit(stu *p){ int i; stu *p1; char name[21]; printf("请输入要修改的姓名:\n"); if (scanf("%20s",name)!=1) return; i=query_value(p,name); if (i<0) { printf("没有找到该学生\n"); return; } p1=query_id(p,i); printf("请输入新的姓名:\n"); if (scanf("%20s",p1->name)!=1) return;
}链表练习--简易模拟学籍管理
https://www.klzy.me/posts/8/分享文章
生成精美分享图或复制链接,与更多人分享本文。
继续阅读
换条路线
从其他文章中稳定抽取
最后更新于 ,距今已过 3313 天
部分内容可能已过时