下列给定程序是建立一个带头结点的单向链表,并用随机函数为各结点数据域赋值。函数proc()的作用是求出单向链表结点(不包括头结点)数据域中的最大值,并且作为函数值返回。请修改程序中的错误,使它能得出正确的结果。
注意:不要改动main()函数,不得增行或删行,也不得更改程序的结构。
试题程序:
#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
typedef struct aa
{ int data;
struct aa*next;
}NoDE;
//****found****
proc(NODE*h)
{ int max=-1;
NODE*P:
p=h->next;
while(p)
{ if(p->data>max)
max=p->data;
//****found****
p=h->next;
}
return max;
}
void outresult(int s,FILE*pf)
{fprintf(pf,"\nThe max in link:%d\n",s);}
NODE*creatlink(int n,int m)
{ NODE*h,*p,*S;
int i;
srand((unsigned)time(NULL));
h=p=(NODE*)malloc(sizeof(NODE));
h->data=9999;
for(i=1;i<=n;i++)
{ s=(NoDE*)malloc(sizeof(NODE));
s->data=rand()%m;s->next=p->next;
p->next=S;p=p->next;
}
p->next=NULL;
return h;
}
void outlink(NODE*h。FILE*pf)
{ NODE*P;
p=h->next;
fprintf(pf,"\n The LIST:\n\n HEAD");
while(p)
{ fprintf(pf,"->%d",p->data);
p=p->next;}
fprintf(pf,"\n");
}
void main()
{ NODE*head;int m;
system("CLS"):
head=creatlink(12,100);
outlink(head,stdout);
m=proc(head):
printf("\nThe RESULT:\n");outresult
(m,stdout);
}
参考答案
答案解析
(1)错误:proc(NODE*h)
正确:int proc(NODE*h)
(2)错误:p=h->next;
正确:p=p->next;
【解析】根据题意,将数据域中的最大值作为函数值返回,可知函数proc()有一个整型的返回值,因此“proc (NODE*h)”应改为“intproc(NODE*h)”;每执行完一次循环,指针P指向其本身结点的下一个结点,因此,“p=h- >next”应改为“p=p->next”。