填空题
给定程序中,函数fun的功能是:计算出带有头结点的单向链表中各结点数据域中值之和作为函数值返回。
请在程序的下划线处填入正确的内容并把下划线删除,使程序得出正确的结果。
#include<stdio.h>
#include<stdlib.h>
#define N 8
typedef struct list
{int data;
struct list *next;
}SLIST;
SLIST*creatlist(int*);
void outlist(SLIST*);
int fun(SLIST*h)
{SLIST *p;int s=0;
p=h->next;
while(p)
{
/**********found**********/
s+=P->
1;
/**********found**********/
p=p->
2;
}
return s;
}
main()
{SLIST*head;
int a[N]={12,87,45,32,91,16,20,48};
head=creatlist(a);outlist(head);
/**********found**********/
printf("/nsum=%d/n",fun(
3));
}
SLIST*creatlist(int a[])
{SLIST*h,*p,*q;int i;
h=p=(SLIST*)malloc(sizeof(SLIST));
for(i=0;i<N;i++)
{q=(SLIST*)malloc(sizeof(SLIST));
q->data=a[i];p->next=q;p=q;
}
P->next=0:
return h;
}
void outlist(SLIST*h)
{SLIST*p;
p=h->next;
if(p==NULL)printf("The list is NULL!/n");
else
{printf("/nHead");
do
{printf("->%dtt,p->data);p=p->next;}
while(p!=NULL);
printf("->End/n");
}
}
【正确答案】
【答案解析】data next head
[解析] 函数fun的功能是计算出链表中各结点数据域中值之和,由于链表单向,利用循环从头结点开始搜索直到最后一个结点,每找到一个结点就把结点的数据域上的数据累加起来。
第一空:循环“while(p)”遍历整个链表,在循环体中,s是累加变量,每个结点的数据域上的数据都累加在s上。因此第一空处应为“s+=p->data;”。
第二空:p是循环变量,p不断指向下一个结点,故第二空处应为“p=p->next;”。
第三空:fun函数的声明为:int fun(SLIST*h),参数是SLIST结构体指针,表示头结点地址。因此第三空处的函数调用应为“printf("/nsum=%d/n",fun(head));”。
[考点] 链表;指针。