• 02-2. 一元多项式求导 (PAT)


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

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

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

    输入样例:

    3 4 -5 2 6 1 -2 0
    

    输出样例:

    12 3 -10 1 6 0


    实现方法:
    根据输入建立链表,链表每个结点包含系数和指数,再对链表进行求导处理。
    实际上使用vector容器更容易解决该问题。
     
    #include <iostream>
    #include <string>
    #include <stdlib.h>
    using namespace std;
    
    typedef struct node{
        int coef;
        int expon;
        struct node *next;
    } *PtrPolyNode, PolyNode;
    
    PtrPolyNode createList();
    void deriPoly( PtrPolyNode headNode );
    void printPoly( PtrPolyNode headNode );
    
    int main()
    {
        PtrPolyNode headNode;
        headNode = createList();
        deriPoly( headNode );
        printPoly( headNode );
        return 0;
    }
    
    PtrPolyNode createList()
    {
        PtrPolyNode headNode = NULL, currentNode = NULL, prevNode = NULL;
        do
        {
            currentNode = (PtrPolyNode)malloc( sizeof( PolyNode ) );
            cin >> currentNode->coef >> currentNode->expon;
            currentNode->next = NULL;
            if ( headNode == NULL )
            {
                headNode = currentNode;
                prevNode = currentNode;
                continue;
            }
            prevNode->next = currentNode;
            prevNode = currentNode;
        }
        while ( cin.get() != '
    ' );
        return headNode;
    }
    
    void deriPoly( PtrPolyNode headNode )
    {
        PtrPolyNode prev, cur;
        cur = prev = headNode;
        if ( headNode->next == NULL && headNode->expon == 0 )    //point
        {
            headNode->coef = 0;
            return;
        }
        while( cur != NULL )
        {
            if ( cur->expon == 0 )    //point
            {
                prev->next = NULL;
                free( cur );
                break;
            }
            cur->coef = cur->coef * cur->expon;
            cur->expon = cur->expon - 1;
            prev = cur;
            cur = cur->next;
        }
        return;
    }
    
    void printPoly( PtrPolyNode headNode )
    {
        PtrPolyNode ptr;
        ptr = headNode;
        while ( ptr != NULL )
        {
            if ( ptr->next == NULL )
            {
                cout << ptr->coef << ' ' << ptr->expon; 
            }
            else
            {
                cout << ptr->coef << ' ' << ptr->expon << ' ';
            }
            ptr = ptr->next;
        }
        return;
    }
  • 相关阅读:
    Senventh Week(补充完整)
    Sixth Week(补充完整)
    Fifth Week(补充完整)
    Fourth Week (补充完整)
    九大内置对象
    matlab 简单绘图
    matlab ./
    困惑
    【转】matlab中inf
    matlab x~=0
  • 原文地址:https://www.cnblogs.com/liangchao/p/4271176.html
Copyright © 2020-2023  润新知