关于链表的一道c语言题!
题目:函数del_node用于从头指针为head的链表中删除数据成员name与字符串str1相等的第一个节点(结构体类型标识符student定义如下)。完成del_node函数
我在完成实验的时候,在进行字符串str1输入的时候老是提示出现内存错误。修改了N久,还是不能运行成功。向各位爱好编程的朋友请教下,万分感谢。
代码如下:
#include<stdio.h>
#include<stdlib.h>
struct student {
char name[9];
int score;
struct student *next;
}*head;
struct student *CreateNode(int nodeNumbers)//创建节点
{
struct student *p;
p=(struct student *)malloc(sizeof(struct student));
if(p==NULL)
{
printf("NO enough memory to alloc");
exit(0);
}
p->next=NULL;
scanf("\n%d %s",&(p->score),p->name);
printf("\nCreate a new node!");
return p;
}
void DispLink(struct student *head)
{
struct student *p;
int j=1;
p=head;
do{
printf("\n%5d%10d %s\n",j,p->score,p->name);
p=p->next;
j++;
}while (p!=NULL);
}
struct student *Del_node(struct student *head, char *str1)
{
// char *str1=NULL;
struct student *p,*pr;
if(head==NULL)
return head;
p=head;
while(strcmp(str1,(p->name))!=0&&p->next!=NULL)
{
pr=p;
p=p->next;
}
if(!strcmp(str1,(p->name)))
{
if(p==head)
head=p->next;
else
pr->next=p->next;
free(p);
printf("delete the node");
}
else
{
printf("\nNot found the Node");
}
return head;
}
main()
{
int i=0;
struct student *pr;
char c;
char arry[9];
char *str1=arry;
head=NULL;
while(1)
{
printf("\nPlease press 'i' to insert one new node");
c=getch();
if(c!='i'&&c!='q')
continue;
if(c=='q')
break;
if(i==0)
{
head=CreateNode(i);
pr=head;
}
else
{
pr->next=CreateNode(i);
pr=pr->next;
}
i++;
}
DispLink(head);
printf("请输入字符串str1:");
scanf("%s",arry);
Del_node(head,str1);
DispLink(head);
}