多项式求导——精选推荐

  • 格式:pdf
  • 大小:34.61 KB
  • 文档页数:1

多项式求导

#include

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;

}