请补充fun函数,该函数的功能是:将带头结点的单向链表逆置。即若原链表中从头至尾结点数据域依次为:2、4、6、8、10,逆置后,从头至尾结点数据域依次为:10、8、6、4、2。
注意:部分源程序给出如下。
请勿改动主函数main和其他函数中的任何内容,仅在函数fun的行线上填入所编写的若干表达式或语句。
[试题源程序]
#include<stdio.h>
#include<stdlib.h>
#define N 5
typedef struct node
int data;
struct node * next;
NODE;
void fun(NODE * h)
NODE*P,*q,*r;
p= (1) ;
if( (2) )return;
q=p->next;
p->next=NULL;
while(q)
r=q->next;
q->next=p;
p=q;
q= (3) ;
h->next=p;
NODE*creatlist(int a[])
NODE*h.*p,*q;int i;
h=(NODE*)malloc(sizeof(NODE));
h->next=NULL;
for(i=0;i<N;i++)
q=(NODE*)malloc(sizeof(NODE));
q->data=a[i];
q->next=NULL;
if(h->next==NULL)
h->next=p=q;
else
P->next=q;p=q;
return h;
void outlist(NODE*h)
NODE*P;
p=h->next;
if(p==NULL)
printf("The list is NULL!\n");
else
printf("\nHead");
do
printf("->%d",p->data);p=p->next;
while(p!=NULL);
printf("->End\n");
main()
NODE*head;
int a[N]=2,4,6,8,10;
head=creatlist(a);
printf("\nThe original list:\n");
outlist(head);
fun(head);
printf("\nThe list after inverting:\n");
outlist(head);
参考答案:r
解析: 填空1:题目明确交代是一个带头结点的单向链表,因此,在函数fun中应该从单向链表的第二个结点开始放入数据,头结点不算,所以指针变量p应该指向h->next。
填空2:这是一个必须的判断语句,即当第一个单元为空时,返回。所以,此处应该填p==NULL。
填空3:链表中的数据交换和数组元素交换的规则是一样的,即使用一个辅助变量进行交换,所以这里应该填r。不同的是链表是通过指针的移动实现对每个结点的访问。