以下是一元多项式的加法运算的C语言实现:

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

ty typedef struct Node *PtrToNode;
struct Node {
    int coef;
    int expon;
    PtrToNode Next;
};
ty typedef PtrToNode Polynomial;

Polynomial ReadPoly();
void Attach(int c, int e, Polynomial *pRear);
Polynomial Add(Polynomial P1, Polynomial P2);
void PrintPoly(Polynomial P);

int main()
{
    Polynomial P1, P2, PP;

    P1 = ReadPoly();
    P2 = ReadPoly();
    PP = Add(P1, P2);
    PrintPoly(PP);

    return 0;
}

Polynomial ReadPoly()
{
    Polynomial P, Rear, t;
    int c, e, N;

    scanf("%d", &N);
    P = (Polynomial)malloc(sizeof(struct Node));
    P->Next = NULL;
    Rear = P;
    while (N--) {
        scanf("%d %d", &c, &e);
        Attach(c, e, &Rear);
    }
    t = P;
    P = P->Next;
    free(t);

    return P;
}

void Attach(int c, int e, Polynomial *pRear)
{
    Polynomial P;

    P = (Polynomial)malloc(sizeof(struct Node));
    P->coef = c;
    P->expon = e;
    P->Next = NULL;
    (*pRear)->Next = P;
    *pRear = P;
}

Polynomial Add(Polynomial P1, Polynomial P2)
{
    Polynomial P, Rear, t1, t2, t;
    int c;

    P = (Polynomial)malloc(sizeof(struct Node));
    P->Next = NULL;
    Rear = P;
    t1 = P1;
    t2 = P2;
    while (t1 && t2) {
        if (t1->expon > t2->expon) {
            Attach(t1->coef, t1->expon, &Rear);
            t1 = t1->Next;
        } else if (t1->expon < t2->expon) {
            Attach(t2->coef, t2->expon, &Rear);
            t2 = t2->Next;
        } else {
            c = t1->coef + t2->coef;
            if (c) Attach(c, t1->expon, &Rear);
            t1 = t1->Next;
            t2 = t2->Next;
        }
    }
    while (t1) {
        Attach(t1->coef, t1->expon, &Rear);
        t1 = t1->Next;
    }
    while (t2) {
        Attach(t2->coef, t2->expon, &Rear);
        t2 = t2->Next;
    }
    t = P;
    P = P->Next;
    free(t);

    return P;
}

void PrintPoly(Polynomial P)
{
    if (!P) {
        printf("0 0\n");
        return;
    }
    printf("%d %d", P->coef, P->expon);
    P = P->Next;
    while (P) {
        printf(" %d %d", P->coef, P->expon);
        P = P->Next;
    }
    printf("\n");
}

该程序的输入格式为:

项数
系数1 指数1
系数2 指数2
...
系数n 指数n

例如,输入:

3
4 3
-1 1
2 0
2
-3 1
1 2

则表示两个多项式分别为:

4x^3 - x + 2
-3x + x^2

程序的输出为它们的和:

4 3 1 2 -1 1 2 0

表示多项式:

x^2 + 4x^3 - x - 3x + 2
C语言实现一元多项式加法运算

原文地址: https://www.cveoy.top/t/topic/lRHl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录