C语⾔数据结构之⼀元多项式的求导//⼀元多项式的求导
#include<stdio.h>
#include<malloc.h>//动态申请空间的函数的头⽂件
typedef struct node  //定义节点类型
{
float coef;        //多项式的系数
int expn;          //多项式的指数
struct node * next; //结点指针域
}PLOYList;
void insert(PLOYList *head,PLOYList *input)  //查位置插⼊新链节的函数,且让输⼊的多项式呈降序排列{
PLOYList *pre,*now;
c语言struct头文件int signal=0;
pre=head;
if(pre->next==NULL) {pre->next=input;} //如果只有⼀个头结点,则把新结点直接连在后⾯
else
{
now=pre->next;//如果不是只有⼀个头结点,则设置now指针
while(signal==0)
{
if(input->expn < now->expn)
{
if(now->next==NULL)
{
now->next=input;
signal=1;
}
else
{
pre=now;
now=pre->next;//始终让新输⼊的数的指数与最后⼀个结点中的数的指数⽐较,⼩于则插在其后⾯
}
}
else if( input->expn > now->expn )
{
input->next=now;
pre->next=input;
signal=1;
}//若新结点中指数⽐最后⼀个结点即now中的指数⼤,则插⼊now之前
else//若指数相等则需合并为⼀个结点,若相加后指数为0则释放该结点
{
now->coef=now->coef+input->coef;
signal=1;
free(input);
if(now->coef==0)
{
pre->next=now->next;
free(now);
}
}//else
} //while
}//else
}//void
PLOYList *creat(char ch)  //输⼊多项式
{
PLOYList *head,*input;
float x;
int y;
head=(PLOYList *)malloc(sizeof(PLOYList));  //创建链表头
head->next=NULL;
scanf("%f %d",&x,&y);//实现⽤户输⼊的第⼀个项,包括其指数和系数
while(x!=0)//当⽤户没有输⼊结束标志0时可⼀直输⼊多项式的项,且输⼊⼀个创建⼀个结点
{
input=(PLOYList *)malloc(sizeof(PLOYList));  //创建新链节
input->coef=x;
input->expn=y;
input->next=NULL;
insert(head,input);  //每输⼊⼀项就将其排序,是的链表中多项式呈降序排列
scanf("%f %d",&x,&y);
}
return head;
}
PLOYList *der(PLOYList *head)//多项式求导
{
PLOYList *p;
p = head -> next;
while (p)
{
p -> coef = p -> coef * p -> expn;
p -> expn = p -> expn--;
p = p -> next;
}
return head;
}//将多项式的每项系数和指数相乘得到新的系数,指数减⼀得到新的指数即完成求导void print(PLOYList *fun)  //输出多项式,fun指要输出的多项式链表的表头
{
PLOYList *printing;
int flag=0;
printing=fun->next;
if(fun->next==NULL)//若为空表,则⽆需输出
{
printf("0\n");
return;
}
while(flag==0)
{
if(printing->coef>0&&fun->next!=printing)
printf("+");
if(printing->coef==1);
else if(printing->coef==-1)
printf("-");
else
printf("%f",printing->coef);
if(printing->expn!=0) printf("x^%d",printing->expn);
else if((printing->coef==1)||(printing->coef==-1))
printf("1");
if(printing->next==NULL)
flag=1;
else
printing=printing->next;
}
printf("\n");
}
void main()
{
PLOYList *f;
printf(" 注:输⼊多项式格式为:系数1 指数1 系数2 指数2 …… ,并以0 0 结束:\n");    printf("请输⼊⼀个⼀元多项式:");
f = creat('f');
printf("这个多项式为:f(x)= ");
print(f);
printf("求导结果为:F(x)=f'(x)= ");
f=der(f);
print(f);
printf("\n\n");
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。