初学数据结构,感觉还是应该多练习才好,于是
写了一个“ADT多项式”的实现,同时也当作一个学习
,代码如下,gcc编译通过,由于写的仓促,注释较少,有什么问题可以给小弟留言。
#include<stdio.h>#define MAX_TERMS 100typedef struct{ float coef; /*系数*/ int expon; /*指数*/} polynomial;polynomial terms[MAX_TERMS-1] = {2,1000,1,0,1,4,10,3,3,2,1,0},temp[MAX_TERMS];int avail = 0;void padd(int,int,int,int,int*,int*);void attach(float,int);int compare(int,int);int compare(int a,int b){ if(a > b) return 1; else if(a == b) return 0; else return -1;}void padd(int starta,int finisha,int startb,int finishb,int* startd,int* finishd){ float coefficient; *startd = avail; while(starta <= finisha && startb <= finishb) switch(compare(terms[starta].expon,terms[startb].expon)) { case -1 : attach(terms[startb].coef,terms[startb].expon); startb++; break; case 0 : coefficient = terms[starta].coef + terms[startb].coef; if(coefficient) attach(coefficient,terms[starta].expon); starta++; startb++; break; case 1 : attach(terms[starta].coef,terms[starta].expon); starta++; break; } for( ; starta <= finisha; starta++) attach(terms[starta].coef,terms[starta].expon); for( ; startb <= finishb; startb++) attach(terms[startb].coef,terms[finishb].expon); *finishd = avail;}void attach(float coefficient,int exponent){ if(avail >= MAX_TERMS) { printf("Too many terms in the polynomial"); return; } temp[avail].coef = coefficient; temp[avail].expon = exponent; avail++;}int main(){ int i,starta = 0,finisha = 1,startb = 2,finishb = 5,startd,finishd; padd(starta,finisha,startb,finishb,&startd,&finishd); printf("polynomial:\n"); for(i = 0;i < finishd;++i) { printf("coef %f expon %d \n",temp[i].coef,temp[i].expon); } return 0;}