请高手帮我改一下这个C语言程序。急~~~~~~~~~~~~

来源:百度知道 编辑:UC知道 时间:2024/09/21 03:17:27
以下程序的“查找(search)”部分有问题,请高手帮我改一下(包括void main中的“查找(search)”)。
#include<stdio.h>
#include<stdlib.h>
#define NULL0
#define LEN sizeof(struct student)
struct student
{long num;
struct student *next;
};
int n;
struct student *creat(void)
{struct student *head;
struct student *p1,*p2;
n=0;
p1=p2=(struct student*)malloc(LEN);
scanf("%ld",&p1->num);
head=NULL;
while(p1->num!=0)
{n=n+1;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student*)malloc(LEN);
scanf("%ld",&p1->num);
}
p2->next=NULL;

return(head);
}
void print(struct student *head)
{struct student *p;
printf("\nThese %d records are:\n",n);
p=head;
if(head!=NULL)
do
{printf("%ld\n",p->num);
p=p->next;
}while(p!=NULL);

针对楼主提出“查找(search)部分有问题”,以下代码修改完成输出查找成功信息:

struct student *search(struct student *head,long e)
{
struct student *p1 = head;
if (p1 == NULL)
{
printf("\nlist null! \n");
}
else
{
for(;p1 != NULL && p1->num != e; p1 =p1->next);
if (p1 != NULL)
{
printf("\nsearch %d successfully.\n", e);
}
}
return(head);
}

另外,程序还有三处内存泄露:
1、函数struct student *creat(void)中代码
p2->next=NULL; 后面应添加
free(p1);
2、函数struct student *del(struct student *head,long num)中代码
n=n-1; 后面应添加
free(p1);
3、函数void main()最后面需要添加释放整个链表的功能,如:
while(head != NULL)
{
stu = head;
free(head);
head = stu->next;
}

有空的话帮你看看