【初学】02-2. 一元多项式求导 (25)

来源:互联网 发布:怎样防止sql注入 编辑:程序博客网 时间:2024/05/16 01:49

PAT的题目,我是用链表实现的,链表实现比较麻烦,用顺序存储会简单些



题目:

02-2. 一元多项式求导 (25)

设计函数求一元多项式的导数。
输入格式:以指数递降方式输入多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式:以与输入相同的格式输出导数多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。注意“零多项式”的指数和系数都是0,但是表示为“0 0”。
输入样例:
3 4 -5 2 6 1 -2 0
输出样例:

12 3 -10 1 6 0



代码:
#include <stdio.h>
#include <stdlib.h>


struct deravationinput
{
int coefficient;
int index;
struct deravationinput *next;
};

struct deravationinput *input()
{
struct deravationinput *head,*p1,*p2;
head=NULL;
int coe,ind;
char c='c';
while(c != '\n')
{
scanf("%d %d",&coe,&ind);
scanf("%c",&c);
p1=(struct deravationinput *)malloc(sizeof(struct deravationinput));
p1->coefficient=coe;
p1->index=ind;
p1->next=NULL;
if(head==NULL)
{
head=p1;
p2=p1;
}
else
{
p2->next=p1;
p2=p1;
}
}

return head;
}


void deravation(struct deravationinput *s)
{
while(s)
{
if(s->index==0)
{
s->coefficient=0;
s->index=0;
s=s->next;
}
else
{
s->coefficient=s->coefficient * s->index;
s->index=s->index-1;
s=s->next;
}
}
}


int main()
{
struct deravationinput *p=input();
deravation(p);
while (p)
{
if(p->next==NULL)
printf("%d %d",p->coefficient,p->index);
else
printf("%d %d ",p->coefficient,p->index);
p=p->next;
}

return 0;

}



0 0
原创粉丝点击