1. 程式人生 > >7-23 一元多項式求導 (20 分)

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);
}