练习1:一组整数已存放在带头结点的单链表中,设计算法,求结点值小于结点平均值的结点个数,并通过函数值返回结果。
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}Node,*LinkList;
int fact(LinkList h);
LinkList h,r,s;
h=(LinkList)malloc(sizeof(Node));
r=h;
int a;
scanf("%d",&a);
while(a!=0){
s=(LinkList)malloc(sizeof(Node));
s->data=a;
r->next=s;
r=s;
scanf("%d",&a);
}free(s);
r->next=0;
return h;
}
int fact(LinkList h){
LinkList p;
p=h->next;
int sum=0,count1=0,count2=0;
double average;
while(p){
sum=sum+p->data;
p=p->next;
count1++;
}average=sum*1.0/count1;
p=h->next;
while(p){
if(p->data<average)count2++;
p=p->next;
}return count2;
}
int main(){
LinkList head;
head=create();
printf("%d",fact(head));
return 0;
}
标签:Node,LinkList,结点,遍历,int,sum,next,链表 From: https://blog.51cto.com/u_16036037/6155258