这么简单的题目自己想想不就出来了
一句话,链表遍历~~
#include
#include
#include
#define NULL 0
typedef struct Polynode
{
float coef;
int exp;
struct Polynode *next;
}Polynode, *Polylist;
void InitPoly(Polylist *P)
{/*初始化,建立只有头结点的空链表(多项式)*/
Polynode *s;
s=(Polynode*)malloc(sizeof(Polynode)); /*申请新的结点*/
s->next=NULL;
*P=s;
}
void CreatePoly(Polylist P)
{/*依次输入多项式的项,建立多项式,直到输入的系数为0为止*/
Polynode *tail, *s;
float c;
int e;
tail=P; /* tail 始终指向单链表的尾,便于尾插法建表*/
scanf("%f,%d",&c,&e); /*键入多项式的系数和指数项*/
while(c!=0.0) /*若c=0.0,则代表多项式的输入结束*/
{
s=(Polynode*)malloc(sizeof(Polynode)); /*申请新的结点*/
s->coef=c;
s->exp=e;
s->next=NULL;
tail->next=s; /*在当前表尾做插入*/
tail=s;
scanf("%f,%d",&c,&e);
}
}
void PrintPoly(Polylist P)
{/*输出多项式*/
Polynode *s;
s=P->next;
printf("\n");
while(s)
{
printf("+%fx^%d",s->coef,s->exp);
s=s->next;
}
printf("\n");
}
void DerivativePoly(Polylist P,Polylist *DP)
{/*求多项式P的导数,结果放在*DP中,它们分别占用不同的存储空间,请同学们完成该函数*/
Polynode *p,*head;
head=(Polynode*)malloc(sizeof(Polynode));
head->next=NULL;
p=P->next;
*DP=head;
while(p)
{
if(p->exp>=1)
{
Polynode *s;
s=(Polynode*)malloc(sizeof(Polynode));
//s->next=head->next;
s->coef=p->coef*p->exp;
s->exp=--(p->exp);
head->next=s;
head=s;
s->next=NULL;
}
p=p->next;
}
}
float power(float x,int n)
{ /*求x的n次方*/
float p=1.0;
int i;
for(i=1;i<=n;i++)
p*=x;
return p;
}
float ValuePoly(Polylist P,float x)
{ /*求多项式的值,请同学们完成该函数*/
Polynode *p;
p=P->next;
float sum=0.0;
while(p)
{
sum+=p->coef*power(x,p->exp);
p=p->next;
}
return sum;
}
void main()
{
Polylist P,Q;
float value1,value2;
float x=1.0;/*自变量x 的值请自拟,可改用键盘输入*/
InitPoly(&P);
CreatePoly(P);
printf("\n创建的多项式为:");
PrintPoly(P);
DerivativePoly(P,&Q);
printf("\n导数多项式为:");
PrintPoly(Q);
value1=ValuePoly(P,x);
value2=ValuePoly(Q,x);
printf("原多项式的值=%f, 导数多项式的值=%f \n",value1,value2);
getchar();
}
祝你好运!
NO