用c语言实现两个一元多项式相加

依然没有配置好vscode,所以还是不知道对不对……

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

typedef struct PolyNode
{
    int coef;
    int expon;
    struct PolyNode *next;
} *Polynomial;

Polynomial InitPolynomial();
void TraverseList(Polynomial l);
void CreatePolynomial(Polynomial l);
Polynomial PolyAdd(Polynomial p1, Polynomial p2);
Polynomial attach(int coef, int expon, Polynomial p);

void main()
{
    Polynomial p1, p2, p;
    p1 = InitPolynomial();
    CreatePolynomial(p1);
    p2 = InitPolynomial();
    CreatePolynomial(p2);
    //TraverseList(p1);
    //TraverseList(p2);
    p = PolyAdd(p1, p2);
    p = p->next;
    TraverseList(p);
}

Polynomial InitPolynomial()
{
    Polynomial p;
    p = (Polynomial)malloc(sizeof(Polynomial));
    if (!p)
    {
        printf("初始化失败");
        exit(1);
    }
    p->next = NULL;
    return p;
}

void TraverseList(Polynomial l)
{
    Polynomial r = l;
    printf("多项式中的元素依次为:");
    while (l)
    {
        printf("系数:%d,指数:%d  ", l->coef, l->expon);
        l = l->next;
    }
    printf("\n");
}

void CreatePolynomial(Polynomial l)
{
    int i, n;
    Polynomial p, r = l;
    printf("请输入多项式的项数:");
    scanf_s("%d", &n);
    printf("请输入多项式的系数和指数(按幂次递减的顺序):");
    scanf_s("%d,%d", &l->coef, &l->expon);
    for (i = 1; i < n; i++)
    {
        p = (Polynomial)malloc(sizeof(Polynomial));
        printf("请输入多项式的系数和指数(按幂次递减的顺序):");
        scanf_s("%d,%d", &p->coef, &p->expon);
        r->next = p;
        r = p;
    }
    r->next = NULL;
}

Polynomial PolyAdd(Polynomial p1, Polynomial p2)
{
    int coef;
    Polynomial r, p;
    p = (Polynomial)malloc(sizeof(Polynomial));
    p->next = NULL;
    r = p;
    while (p1 && p2)
    {
        if (p1->expon == p2->expon)
        {
            coef = p1->coef + p2->coef;
            if (coef)
                p = attach(coef, p1->expon, p);
            p1 = p1->next;
            p2 = p2->next;
        }
        else if (p1->expon > p2->expon)
        {
            p = attach(p1->coef, p1->expon, p);
            p1 = p1->next;
        }
        else
        {
            p = attach(p2->coef, p2->expon, p);
            p2 = p2->next;
        }
    }
    for (; p1; p1 = p1->next) p = attach(p1->coef, p1->expon, p);
    for (; p2; p2 = p2->next) p = attach(p2->coef, p2->expon, p);
    return r;
}

Polynomial attach(int coef, int expon, Polynomial p)
{
    Polynomial r;
    r = (Polynomial)malloc(sizeof(Polynomial));
    r->coef = coef;
    r->expon = expon;
    r->next = p->next;
    p->next = r;
    p = r;
    return p;
}
最后修改:2020 年 08 月 30 日 09 : 14 PM
如果觉得我的文章对你有用,请随意赞赏