1、f)/求k阶斐波那契序列的第m项的值fint tempd;if(k2|m0) return ERROR;if(mk-1) f=0;else if (m=k-1) f=1;elsefor(i=0;i=k-2;i+) tempi=0;tempk-1=1; /初始化for(i=k;=m;i+) /求出序列第k至第m个元素的值sum=0;for(j=i-k;ji;j+) sum+=tempj;tempi=sum;f=tempm;return OK;/fib分析:通过保存已经计算出来的结果,此方法的时间复杂度仅为O(m2).如果采用递归编程(大多数人都会首先想到递归方法),则时间复杂度将高达O(km).
2、 1.18 typedef struct char *sport;enummale,female gender;char schoolname; /校名为A,BCD或Echar *result;int score; resulttype; int malescore;int femalescore;int totalscore; scoretype;void summary(resulttype result )/求各校的男女总分和团体总分,假设结果已经储存在result 数组中scoretype score;i=0;while(resulti.sport!=NULL)switch(resul
3、ti.schoolname)case :score 0 .totalscore+=resulti.score;if(resulti.gender=0) score 0 .malescore+=resulti.score;else score 0 .femalescore+=resulti.score;break;score.totalscore+=resulti.score;if(resulti.gender=0) score.malescore+=resulti.score;else score.femalescore+=resulti.score;i+;5;i+)printf(School
4、 %d:n,i);Total score of male:%dn,scorei.malescore);Total score of female:,scorei.femalescore);Total score of all:%dnn,scorei.totalscore);/summary 1.19 Status algo119(int aARRSIZE)/求i!*2i序列的值且不超过maxintlast=1;for(i=1;=ARRSIZE; ai-1=last*2*i; if(ai-1/last)!=(2*i) reurn OVERFLOW; last=ai-1; return OK;/a
5、lgo119当某一项的结果超过了maxint时,它除以前面一项的商会发生异常. 1.20 void polyvalue()float ad;float *p=a;Input number of terms:);scanf(%dn);Input the %d coefficients from a0 to a%d:,n,n);=n;i+) scanf(%f,p+);Input value of x:x);p=a;xp=1; /xp用于存放x的i次方sum+=xp*(*p+);xp*=x;Value is:,sum);/polyvalue第二章 线性表 2.10 Status DeleteK(Sq
6、List &a,int i,int k)/删除线性表a中第i个元素起的k个元素if(i1|ka.length) return INFEASIBLE;for(count=1;i+count-1va.listsize) return ERROR;va.length+;for(i=va.length-1;va.elemix&i=0;i-)va.elemi+1=va.elemi;va.elemi+1=x;/Insert_SqList 2.12 int ListComp(SqList A,SqList B)/比较字符表A和B,并用返回值表示结果,值为正,表示AB;值为负,表示Anext;p&p-data
7、!=x;p=p-next);return p;/Locate 2.14 int Length(LinkList L)/求链表的长度for(k=0,p=L;next,k+);return k;/Length 2.15 void ListConcat(LinkList ha,LinkList hb,LinkList &hc)/把链表hb接在ha后面形成链表hchc=ha;p=ha;while(p-next) p=p-next=hb;/ListConcat 2.16 见书后答案. 2.17 Status Insert(LinkList &L,int i,int b)/在无头结点链表L的第i个元素之前
8、插入元素bp=L;q=(LinkList*)malloc(sizeof(LNode);q.data=b;if(i=1)q.next=p;L=q; /插入在链表头部while(-i1) p=p-q-next=p-next=q; /插入在第i个元素的位置/Insert 2.18 Status Delete(LinkList &L,int i)/在无头结点链表L中删除第i个元素if(i=1) L=L- /删除第一个元素next- /删除第i个元素/Delete 2.19 Status Delete_Between(Linklist &L,int mink,int maxk)/删除元素递增排列的链表L中值大于mink且小于maxk的所有元素data /p是最后一个不大于mink的元素if(p-next)/如果还有比mink更大的元素q=p-while(q-maxk) q=q- /q是第一个不小于maxk的元素/Delete_Between 2.20 Status Delete_Equal(Linklist &L)/删除元素递增排列的链表L中所有值相同的元素p=L- /p,q指向相邻两元素next)=q-data) /当相邻两元素不相等时,p,q都向后推一步data=p-data) free(q); q=q- p=q; /当相邻元素相等时删除多余元素/else/whil
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1