链表——一元多项式求导

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

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

输入格式:

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

输出格式:

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

输入样例:

3 4 -5 2 6 1 -2 0

输出样例:

12 3 -10 1 6 0

//多项式
// 3 4 -5 2 6 1 -2 0
// 3x^4 -5x^2 + 6x -2
//输出 12 3 -10 1 6 0
//即求导结果 : 12x^3 -10x + 6 - 0

#include<stdio.h>
#include<iostream>
#include<stdlib.h>

#define MAXSIZE 100
#define OK 1
#define ERROR 0

using namespace std;
typedef int Status;
typedef int Elemtype;
typedef struct LNode *List;
typedef struct LNode
{
    Elemtype coef;//系数
    Elemtype expon;//指数
    struct LNode *next;//指针指向下一个结点
} LNode, *LinkList;

Status InitList(LinkList &L)
{
    L = new LNode;
    L ->next = NULL;
    return OK;
}
int Length(LinkList &L)//求长度
{
    int len = 0;
    LNode* p;
    p = L -> next;
    while(p)
    {
        p = p->next;
        len++;
    }
    return len;
}
void ReadList(LinkList &L)//读取一个多项式
{
    L = new LNode;
    L -> next = NULL;
    LNode *r,*p;
    r = L;
    p = new LNode;

    Elemtype c,x;
    while(cin>>c>>x)
    {
        p = new LNode;
        p -> coef = c;
        p -> expon = x;
        p -> next = NULL;
        r -> next = p;
        r = p;
    }
}
void DerivList(LinkList &L1,LinkList &L2)//求导
{
    LNode *p;
    p = L1 -> next;
    LNode *cur,*rear;
    cur = L2;
    rear = new LNode;

    while(p)
    {
        if(p->coef!=0&&p->expon!=0)
        {
            rear = new LNode;
            rear -> coef = (p->coef) *  (p->expon);
            rear -> expon = p->expon -1;
            rear -> next = NULL;
            cur -> next = rear;
            cur = rear;
        }
        p = p->next;
    }
}
void PrintList(LinkList &L)//输出
{
    if(!Length(L))
        cout<<"0 0";
    else
    {
        LNode *p;
        p = L->next;
        while(p)
        {
            if(p->next != NULL)
            {
                cout<<p->coef<<" "<<p->expon<<" ";
            }
            else
            {
                cout<<p->coef<<" "<<p->expon<<endl;
            }
            p = p -> next;
        }
    }
}
int main()
{
    LinkList L1,L2;
    InitList(L1);
    InitList(L2);

    ReadList(L1);

    DerivList(L1,L2);
    PrintList(L2);
}



猜你喜欢

转载自blog.csdn.net/Yolanda_Salvatore/article/details/78830113