问题 问答题

请编写函数fun(),它的功能是:将带头结点单向链表按data域由大小排序(排序时不考虑头结点),主函数用随机函数为各结点data域赋值,头结点data域赋值为0。
注意:部分原程序给出如下。
请勿改动主函数main和其他函数中的任何内容,仅在函数fun的花括号中填入所编写的若干语句。
[试题源程序]
#include <stdio.h>
#include <conio.h>
struct aa

int data;
struct aa*next;

void fun(struct aa*p)


main()

int i,n,m=100;
struct aa*h=NULL,*s=NULL,
*p=NULL;
clrscr();
S=(struct aa*)malloc(sizeof(struct aa));
h=s;h->data=0;h->next=NULL;
printf("Please input n:");
scanf("%d",&n);
for(i=1;i<=n;i++)

p=(struct aa*)malloc(sizeof(struct aa));
p->data=rand()%m;p->next=NULL;
printf("%d",p->data);
s->next=p;s=s->next;

fun(h);
printf("\n");
for(h=h->next;h!=NULL;h=h->nnext)
printf("%d",h->data);

答案

参考答案:void fun(struct aa*p)
{
int temp;
struct aa*1st;
for(p=p->next;P->next!=NULL;p=p->next)
for(1st=p->next;1st!=NULL;1st=1st->next)
if(1st->data>p->data)
{
temp=1st->data;
1st->data=p->data;
p->data=temp;
}
}

解析: 本题考查单链表的操作。为了交换需定义中间变量,本题可以采用选择排序法进行排序。基本方法和对数组进行排序相似,只不过是通过指针的移动实现对比较次数的控制和每个结点的访问,注意循环结束的控制条件。

选择题
单项选择题