C语言单链表的问题 为什么不能一下删除所有节点,同时switch语句的case1,3,4哪里错了,求指点
//源代码如下#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Student
{
int number;
char *name;
char *addr;
int math;
int computer;
struct Student *next;
};
struct Student *create_head(struct Student *head)
{
head=NULL;
return head;
}
//增加学生
void add_stu(struct Student **head,int number,char *name,char *addr,int math,int computer)
{
struct Student *p=(struct Student *)malloc(sizeof(struct Student));
struct Student *p2=*head;
if(p==NULL)
{
printf("内存空间分配失败!\n");
exit(0);
}
p->number=number;
p->name=(char *)malloc(strlen(name)+1);
strcpy(p->name,name);
p->addr=(char *)malloc(strlen(addr)+1);
strcpy(p->addr,addr);
p->math=math;
p->computer=computer;
p->next=NULL;
if(*head==NULL)
{
*head=p;
return;
}
else
{
while(p2->next!=NULL)
{
p2=p2->next;
}
p2->next=p;
}
return;
}
//打印学生
void print_stu(struct Student *head)
{
struct Student *p=head;
if(head==NULL)
{
printf("还未添加一个学生!\n");
return;
}
else
{
while(p!=NULL)
{
printf("学号:%d\t姓名:%s\t地址:%s\t数学成绩:%d\t计算机成绩:%d\n",p->number,p->name,p->addr,p->math,p->computer);
p=p->next;
}
}
return;
}
//根据姓名删除
void delete_by_name(struct Student *head,char *name)
{
struct Student *p=head;
struct Student *p2;
if(head==NULL)
{
return;
}
while(p!=NULL)
{
if(strcmp(p->name,name)==0)
{
p2->next=p->next;
free(p->addr);
free(p->name);
free(p);
break;
}
else
{
p2=p;
p=p->next;
}
}
return;
}
//删除所有
void delete_all(struct Student **head)
{
struct Student *p=*head;
if(*head==NULL)
{
return;
}
while((*head)->next!=NULL)
{
p=(*head)->next;
(*head)->next=p->next;
free(p->addr);
free(p->name);
free(p);
}
return;
}
//根据姓名打印
void print_name(struct Student *head,char *name)
{
struct Student *p=head;
if(head==NULL)
{
return;
}
while(p!=NULL)
{
if(strcmp(p->name,name)==0)
{
printf("学号:%d\t姓名:%s\t地址:%s\t数学成绩:%d\t计算机成绩:%d\n",p->number,p->name,p->addr,p->math,p->computer);
break;
}
else
{
p=p->next;
}
}
if(p==NULL)
{
printf("没有 %s 的信息!\n",name);
}
}
int main()
{
int j=0;
int snum,smath,scomputer;
char *sname;
char *saddr;
int number1=1111;
char *name1="zhangsan";
char *addr1="yinchuan";
int math1=88;
int computer1=73;
struct Student *head=create_head(head);
add_stu(&head,number1,name1,addr1,math1,computer1);
add_stu(&head,1112,"lisi","shanghai",92,83);
add_stu(&head,1113,"wangwu","beijing",85,91);
print_stu(head);
// delete_by_name(head,"lisi");
//print_stu(head);
//delete_all(&head);
print_stu(head);
//print_name(head,"lisiwww");
printf("输入1增加学生,输入2打印学生,输入3 根据姓名打印学生,输入4根据姓名删除学生,输入5删除所有学生,输入其他数字退出:\n");
scanf("%d",&j);
switch(j)
{
case 1:
scanf("%d,%s,%s,%d,%d",&snum,sname,saddr,&smath,&scomputer);
add_stu(&head,snum,sname,saddr,smath,scomputer);
break;
case 2:
print_stu(head); //打印学生
break;
case 3:
scanf("%s",sname);
print_name(head,sname);
break;
case 4:
scanf("%s",sname);
delete_by_name(head,sname);
break;
case 5:
delete_all(&head);
break;
default:
exit(0);
break;
}
print_stu(head);
return 0;
}