帮我看下这个链表程序,哪里错了
在VC里运行,查找的时候需要输入两次学号,删除结点的时候提示“内存不能为"read"”, 不知道什么原因,烦请各位帮忙看下。
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct student
{
int num;
float score;
struct student *next;
};
struct student *create_head()
{
struct student *head;
head=(struct student*)malloc(sizeof(struct student));
if(head==NULL)
{
printf("申请头结点失败!\n");
return NULL;
}
else
head->next=NULL;
}
struct student *Insert(struct student *head, struct student *s)
{
struct student *p=head;
while(p->next!=NULL&&s->score>p->next->score)
p=p->next;
if(p==NULL)
{
p->next=s;
s->next=NULL;
}
else
{
s->next=p->next;
p->next=s;
}
return head;
}
struct student *search(struct student *head)
{
int num;
struct student *p=head->next;
printf("请输入要查找结点的学号:\n");
scanf("%d\n",&num);
while(p!=NULL&&p->num!=num)
p=p->next;
if(p=NULL)
{
printf("没有找到学号为%d的结点!\n",num);
return NULL;
}
else
{
printf("找到学号为%d的结点\n该结点为%d\t%f\n",num,p->num,p->score);
return p;
}
}
void print(struct student *head)
{
struct student *p=head->next;
while(p!=NULL)
{
printf("%d\t%.1f\n",p->num,p->score);
p=p->next;
}
}
void free_list(struct student *head)
{
struct student *p=head;
while(p!=NULL)
{
head=head->next;
free(p);
p=head;
}
printf("释放链表成功!\n");
}
struct student *delenote(struct student *head, int num_x)//删除学号为num_x的结点
{
struct student *p1=head,*p2=head->next;
while(p2!=NULL&&p2->num!=num_x)
{
p2=p2->next;
p1=p1->next;
}
if(p2==NULL)
{
printf("没有找到要删除的结点!\n");
}
else
{
p1->next=p2->next;
free(p2);
printf("删除结点成功!\n");
}
return head;
}
void main()
{
struct student *head,*p;
int num;
float score;
char c;
printf("有头结点链表操作程序:\n");
printf("I:插入结点(自动升序) P:打印链表 S:查找结点 D:删除结点 F:释放链表并退出程序");
head=create_head();
while(1)
{
c=getchar();
switch(c)
{
case 'I': printf("请输入要插入学生的学号和分数:\n");
scanf("%d%f\n",&num,&score);
p=(struct student *)malloc(sizeof(struct student));
if(p==NULL)
{
printf("申请结点失败!\n");
exit(0);
}
else
{
p->num=num;
p->score=score;
Insert(head,p);
printf("插入成功\n");
}
break;
case 'P': print(head);
break;
case 'S': search(head);
break;
case 'D':printf("请输入要删除学生的学号:\n");
scanf("%d\n",&num);
delenote(head,num);
break;
case 'F':free_list(head);
exit(0);
}
}
}