PTA 7-2一元多项式求导

#include<stdio.h>
#include<stdlib.h>
typedef struct term {
    int coef;
    int exp;
    struct term* next;
} term;

void printfpoly(term* polynomial) {
    int first = 1;
    term* p = polynomial;
    while (p!=NULL) {
        if (first == 1) {
            printf("%d %d", p->coef, p->exp);
            first = 0;
        }else{
            printf(" %d %d", p->coef, p->exp);
        }
        
        p = p->next;
    }
}

term* derivative(term* polynomial) {
    term* p = polynomial;
    term* q = NULL;
    if(p->next!=NULL){
    	while (p) {
        if (p->exp == 0||p->coef==0) {
            if (q) {
                q->next = p->next;
            }
            else {
                polynomial =p ->next;
            }
            p = p->next;
        }
        else {
            p->coef *= p->exp;
            p->exp -= 1;
            q = p;
            p = p->next;
        }
      }
	}else{
		if(p->exp==0){
			p->coef=0;
		}else{
			p->coef=p->exp*p->coef;
			p->exp--;
		}
	}

    return polynomial;
}

term* makelist() {
    term* head, * tail;
    head = tail = NULL;
    int coef, exp;
    while (scanf("%d %d", &coef, &exp) == 2) {
        term* p = (term*)malloc(sizeof(term));
        p->coef = coef;
        p->exp = exp;
        p->next=NULL;
        if (head == NULL) {
            head = tail = p;
        }
        else {
            tail->next = p;
            tail = p;
        }
    }
    return head;
}

int main() {
    term* polynomial = makelist();
    polynomial = derivative(polynomial);
    printfpoly(polynomial);
    return 0;
}

derivative()函数在实现时逻辑为:一:当多项式只有一项时,求导后为0多项式(1:指数为0,输出:0 0,    2:当系数为0,指数不为0,输出:0 求导后的指数。)

二:当多项式为至少两项时,在求导后为0多项式的要删去。本题系数为0时输出或不输出都为对

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值