题解 | #记负均正II#
记负均正II
https://www.nowcoder.com/practice/64f6f222499c4c94b338e588592b6a62
#include <stdio.h> #include <stdlib.h> struct number{ int num; struct number *next; // struct number *prev; }; int findNumber(struct number *pointer) { struct number *p = pointer; int cnt=0; while(p) { if(p->num<0) { cnt++; } p=p->next; } return cnt; } float getAverage(struct number *pointer) { struct number *p = pointer; float sum=0.0,average=0.0; int cnt=0; while(p) { if(p->num>0) { sum+=p->num; cnt++; } p=p->next; } if(cnt>0) { return average=sum/cnt; } return 0.0; } int main() { float average=0.0; int a,count=0; // printf("zheli ok"); struct number *head=NULL,*end=head; while (scanf("%d", &a) != EOF) { // 注意 while 处理多个 case // printf("zheli ok"); struct number *newnode = (struct number *)malloc(sizeof(struct number)); newnode->num=a; newnode->next=NULL; if(head==NULL) { head=newnode; end=head; } end->next=newnode; end=newnode; if(end->next!=NULL) { end->next=NULL; } count=findNumber(head); average=getAverage(head); // while(head) // { // printf("%d ",head->num); // head=head->next; // } } printf("%d\n%.1f",count,average); return 0; }
这里使用单链表保存输入数据,避免了一次性开辟大数组带来的坏处。需要注意的是链表只有一个节点时,头指针和尾指针都指向同一节点。