PAT001 一元多项式求导

题目:

设计函数求一元多项式的导数。(注:xn(n为整数)的一阶导数为n*xn-1。)

输入格式:以指数递降方式输入多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。

输出格式:以与输入相同的格式输出导数多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。注意“零多项式”的指数和系数都是0,但是表示为“0 0”。

输入样例:

3 4 -5 2 6 1 -2 0

输出样例:

12 3 -10 1 6 0

分析: 主要考查通过链表进行线性结构的存储,注意输入终止判断以及链表插入操作

C语言(因为提交时出现NULL报错,所以将NULL替换成了0 导入#include <stdio.h>即可使用NULL)
typedef struct Node{
    int coe; // 系数
    int exp; // 指数
    struct Node *next; // 下一项
} List;

typedef struct head {
    struct Node *begin;
    struct Node *end;
} NodeHead;

List *insert(int coe, int exp, NodeHead *ptrl);

int main()
{
    NodeHead *head = (NodeHead *)malloc(sizeof(NodeHead));
    head->begin = 0;
    head->end = 0;
    
    int tempCoe, tempExp;
    while (scanf("%d %d", &tempCoe, &tempExp) != 0) {
        insert(tempCoe, tempExp, head);
        if (getchar() == '
') {
            break;
        }
    }
    
    List *ptr = head->begin;
    if (ptr) {
        if (ptr->coe * ptr->exp == 0) {
            printf("0 0");
        } else {
            printf("%d %d", ptr->coe * ptr->exp, ptr->exp - 1);
        }
        ptr = ptr->next;
        while (ptr) {
            if (ptr->coe * ptr->exp == 0) {
                // printf(" 0 0");
            } else {
                printf(" %d %d", ptr->coe * ptr->exp, ptr->exp - 1);
            }
            ptr = ptr->next;
        }
    }
}

List *insert(int coe, int exp, NodeHead *head)
{
    List *l = (List *)malloc(sizeof(List));
    
    if (!(head->begin)) {
        head->begin = l;
    }
    
    List *end = head->end;
    if (end) {
        end->next = l;
    }
    head->end = l;
    
    l->coe = coe;
    l->exp = exp;
    
    return l;
}

运行结果

原文地址:https://www.cnblogs.com/liufeng24/p/4392566.html