多项式求导

#include<iostream>
using namespace std;
class poly{
public:
int coef;
int expon;
poly *next;
};
poly*input(); /*输入函数*/
poly*attach(poly*rear, int c, int e); /*链接函数,连接求导后的结果*/
poly*func(poly*head); /*实现求导的函数*/
int main(){
poly*p;
p = input();
p = func(p);
while (p){
cout << p->coef << " " << p->expon << (p->next==NULL?'\n':' ');
p = p->next;
}
return 0;
}
poly*input(){
poly*p = new poly; /*申请新空间*/
poly*head = p, *p1 = p;
while (cin >> p->coef >> p->expon){
char ch = getchar();
p1 = p;
p = new poly;
p1->next = p;
if (ch == '\n') /*碰到换行键跳出*/
break;
}
delete p; /*删除最后末尾的空节点*/
p1->next = NULL;
return head; /*返回头结点*/
}
poly * attach(poly*rear, int c, int e){
poly*p = new poly; /*插入先申请空间*/
p->coef = c;
p->expon = e;
rear->next = p;
rear = p;
return rear; /*返回末尾指针*/
}
poly*func(poly*p){
poly*head = new poly; /*申请一个空节点*/
poly*rear = head;
if (p->expon == 0){ /*如果只有常数项,分开做处理*/
p->coef = 0;
return p;
}
while (p&&p->expon){ /*跳出条件为p为空或者p的指数为o,对于求导来说,指数为0的可以省略*/
p->coef = p->coef*p->expon;
p->expon--;
rear = attach(rear, p->coef, p->expon);
p = p->next;
}
rear->next = NULL; /*扫尾工作*/
poly*temp = head;
head = head->next; //头结点移到下一位
delete temp; //删除空的头结点
return head;
}

posted @ 2015-04-14 22:28  曹孟德  阅读(684)  评论(0编辑  收藏  举报