仅供参考,共同进步。

7-23 一元多项式求导 (20 分)

7-23 一元多项式求导 (20 分)

设计函数求一元多项式的导数。

输入格式:

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

输出格式:

以与输入相同的格式输出导数多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。

输入样例:

3 4 -5 2 6 1 -2 0

  

输出样例:

12 3 -10 1 6 0

  第一次做:

#include <stdio.h>
#include <malloc.h>
typedef int ElemType;

typedef struct LNode
{
    ElemType real;
    ElemType index;
    struct LNode *next;
}LNode, *LinkList;
int main()
{
    LinkList L;
    LNode *temp, *head;
    L = (LNode *)malloc(sizeof(LNode));
    L->next = NULL;
    head = L;

    int index, real;
    while(scanf("%d %d", &real, &index)!=EOF){
        temp = (LNode *)malloc(sizeof(LNode));
        temp->next = NULL;
        if(index != 0){
            temp->real = real * index;
            temp->index = index - 1;
            head->next = temp;
            head = temp;
        }
    }
    head = L->next;
    if(!head)
    printf("0 0");
    while(head){
        if(head->next == NULL)
            printf("%d %d", head->real, head->index);
        else
            printf("%d %d ", head->real, head->index);
        head = head->next;
    }
}

  第二次做:

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct LNode
{
    int Coef;
    int index;
    struct LNode * next;
}LNode, *List;
void CreatList(List &L)
{
    L = (LNode*)malloc(sizeof(LNode));
    L->next = NULL;
    LNode *temp, *p = L;
    int coef, index;
    while(scanf("%d %d", &coef, &index)!=EOF){
        temp = (LNode*)malloc(sizeof(LNode));
        temp->next = NULL;
        temp->Coef = coef;
        temp->index = index;
        p->next = temp;
        p = temp;
    }
}
void Derivation(List &L)
{
    LNode *p = L->next;
    LNode *pre = L;
    while(p != NULL){
        if(p->index != 0){
            p->Coef *= p->index;
            p->index -= 1;
        }
        else{
            pre->next = p->next;
        }
        pre = pre->next;
        p = p->next;
    }
}
void Output(List L)
{
    L = L->next;
    if(L == NULL){
        printf("0 0\n");
        return ;
    }
    while(L != NULL){
        if(L->next != NULL)
            printf("%d %d ", L->Coef, L->index);
        else
            printf("%d %d\n", L->Coef, L->index);
        L = L->next;
    }
}
int main()
{
    List L;
    CreatList(L);
    Derivation(L);
    Output(L);
}

  

posted @ 2018-12-18 23:10  南山i  阅读(1789)  评论(0编辑  收藏  举报