跳到正文

个人记录

多项式的求和

XHCuteDog约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年6月21日
更新
2026年6月21日
篇幅
约 5 分钟

版本

  1. v1当前
C
//分别读入两个多项式的系数和指数,用逗号隔开,每个多项式输入结束用0,0表示
//输出一个多项式 是输入的两个多项式的和 只需要输出“系数,指数”形式即可
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct node {
    int coef;//系数
    int expon;//指数
    struct node* Next;
} Poly_Clu, * List;//Poly_Clu就是指代结构体 而List是一个指针
int Compare(int expon1, int expon2)
{
    if (expon1 > expon2)
        return 1;
    else if (expon1 < expon2)
        return -1;
    else
        return 0;
}
List List_create()//链表的构建
{
    List L = (List)malloc(sizeof(Poly_Clu));//给L赋予初始的空间 用来存储 灵活不固定的
    L->Next = NULL;
    int coef, expon;
    Poly_Clu* temp = L;//用来构建链表 并且记录当前表的尾位置
    Poly_Clu* p;//新来的一个结点
    scanf_s("%d,%d", &coef, &expon);
    while (!(coef == 0 && expon == 0))
    {
        p = (Poly_Clu*)malloc(sizeof(Poly_Clu));
        p->coef = coef;
        p->expon = expon;
        p->Next = NULL;
        temp->Next = p;
        temp = p;
        scanf_s("%d,%d", &coef, &expon);
    }
    return L;//返回链表的初始位置。
}
void Attach(int coef, int expon, List* L_Rear)//在当前答案多项式的尾部添加
{
    List P;
    P = (List)malloc(sizeof(Poly_Clu));
    P->coef = coef;
    P->expon = expon;
    P->Next = NULL;
    (*L_Rear)->Next = P;
    *L_Rear = P;
}

List PolyAdd(List P1, List P2)
{
    int sum;//处理相同指数时候使用
    List front, rear, tempt;
    rear = (List)malloc(sizeof(Poly_Clu));
    front = rear;
    while (P1 && P2)
    {
        int a = Compare(P1->coef, P2->coef);
        switch (a)
        {
        case 1:
            Attach(P1->coef, P1->expon, &rear);
            P1 = P1->Next;
            printf("1");
            break;
        case -1:
            Attach(P2->coef, P2->expon, &rear);
            P2 = P2->Next;
            printf("-1");
            break;
        case 0:
            sum = P1->coef + P2->coef;
            if (sum)
                Attach(sum, P1->expon, &rear);
            P1 = P1->Next;
            P2 = P2->Next;
            printf("好耶,系数和为0");
            break;
        }
    }
    while (P1)
    {
        Attach(P1->coef, P1->expon, &rear);
        P1 = P1->Next;
    }
    while (P2)
    {
        Attach(P2->coef, P2->expon, &rear);
        P2 = P2->Next;
    }
    rear->Next = NULL;
    tempt = front;
    front = front->Next;
    free(tempt);//使得front指向结果多项式的第一位地址
    return front;
}

int main()
{
    List L1 = List_create();
    List L2 = List_create();
    List Ans_L = PolyAdd(L1, L2);
    printf("Ans 的地址%p", Ans_L);
    while (L1)
    {
        printf("%d,%d L1链表\n", L1->coef, L1->expon);
        L1 = L1->Next;
    }
    while (L2)
    {
        printf("%d,%d L2链表\n", L2->coef, L2->expon);
        L2 = L2->Next;
    }
    while (Ans_L)
    {
        printf("%d,%d ", Ans_L->coef, Ans_L->expon);
        Ans_L = Ans_L->Next;
    }
    return 0;
}
原文