#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct students{
char name[10];
int num;
float score;
struct students *next;
};
int count=0;
int *p = &count;
void getInfo(struct students *);
void addStu(struct students **);
int delStu(struct students **,int );
int searchStu(struct students *,int );
void showList(struct students **);
int main(){
struct students *S = NULL;//生成一个头节点
int op,i;
do{
printf("welcome to students' information manage system!\n");
printf("please chose your operation:\n");
printf("1 add a student to specified location\n");
printf("2 delete a student from the specified location\n");
printf("3 find a student through his number\n");
printf("4 show the list:\n");
printf("0 exit\n");
scanf("%d",&op);
switch(op){
case 1:printf("input the student information:");addStu(&S);break;
case 2:printf("input the num you want to delete:");scanf("%d",&i);delStu(&S,i);break;
case 3:printf("input his num:");scanf("%d",&i);searchStu(S,i);break;
case 4:showList(&S);break;
}
}while(op != 0);
return 0;
}
void getInfo(struct students *s){
printf("input students's name :\n");
scanf("%s",s->name);
printf("input students's num and score:\n");
scanf("%d%f",&s->num,&s->score);
}
void addStu(struct students **S1){
struct students *ns,*temp,*move = (struct students * const)S1;
ns = (struct students *)malloc(sizeof(struct students));
if(ns == NULL){
printf("menory allocation error!");
exit(1);
}
getInfo(ns);
if(*S1 == NULL){ //空链表的操作;
move=ns;
ns->next=NULL;
// move = move->next;
}
else{
while(move->num<ns->num && move->next != NULL){//通过新学生的学号来移动move与temp指针,
temp = move;
move = move->next;
}
if(move == *S1){ //如果新来的学生的学号是最小的,那么move指针并不会移动,所以move指针指向头节点
ns->next = move->next;
move = ns;
}
else if(move->next == NULL && move->num<ns->num){ //新学生的学号是最大的
move->next = ns;
ns->next = NULL;
}
else{ //学生学号刚好在中间
temp->next = ns;
ns->next = move;
}
}
printf("%s\t%d\t%d\t\n",move->name,move->num,move->score);
// printf("%s\t%d\t%d\t\n",(*S1)->name,(*S1)->num,(*S1)->score);
}
int delStu(struct students **S1,int n){
struct students *temp,*ptr = *S1; //用来接收旧的结构体节点,并准备释放内存
if(ptr->next == NULL){
printf("can't delete student from an empty list\n");
}
while(ptr->num < n){
ptr=ptr->next;
}
if(ptr == NULL){
printf("can't find this student!\n");
}
if(ptr->num == n){
temp = ptr;
ptr = temp->next;
free(temp);
printf("delete complete\n");
}
return 0;
}
int searchStu(struct students *S1,int n){
int i = 0;
while(S1 != NULL){
if(S1->num == n){
printf("he/she is the %d student",i);
return i+1;
}
S1 = S1->next;
i++;
}
if(S1->next == NULL && S1->num != n){
printf("can't find this student");
return 0;
}
return 0;
}
void showList(struct students **S1){
struct students *s;
s = *S1;
if(*S1 == NULL){
printf("no student in this list!\n");
}
else{
printf("name\tnum\tscore\t\n");
}
while(s != NULL){
printf("%s\t%d\t%d\t\n",s->name,s->num,s->score);
s = s->next;
}
}
使用常指针的代码,但是不知道为什么,*S1就是一直是空的,求大佬们看看思路哪里有错吧
|