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

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

// 定义多项式结构体
typedef struct node {
    int coefficient;  // 系数
    int exponent;     // 指数
    struct node *next;
} Node;

// 创建多项式
Node *create() {
    Node *head = (Node *)malloc(sizeof(Node));
    head->next = NULL;
    return head;
}

// 插入节点
void insert(Node *head, int coefficient, int exponent) {
    Node *p = head;
    Node *q = p->next;
    while (q != NULL && q->exponent > exponent) {
        p = q;
        q = q->next;
    }
    if (q != NULL && q->exponent == exponent) {
        q->coefficient += coefficient;
        if (q->coefficient == 0) {
            p->next = q->next;
            free(q);
        }
    } else {
        Node *new_node = (Node *)malloc(sizeof(Node));
        new_node->coefficient = coefficient;
        new_node->exponent = exponent;
        new_node->next = q;
        p->next = new_node;
    }
}

// 输出多项式
void print(Node *head) {
    Node *p = head->next;
    while (p != NULL) {
        printf('%dX^%d', p->coefficient, p->exponent);
        p = p->next;
        if (p != NULL) {
            printf(' + ');
        }
    }
}

// 多项式加法
Node *add(Node *a, Node *b) {
    Node *c = create();
    Node *p = a->next;
    Node *q = b->next;
    while (p != NULL && q != NULL) {
        if (p->exponent > q->exponent) {
            insert(c, p->coefficient, p->exponent);
            p = p->next;
        } else if (p->exponent < q->exponent) {
            insert(c, q->coefficient, q->exponent);
            q = q->next;
        } else {
            insert(c, p->coefficient + q->coefficient, p->exponent);
            p = p->next;
            q = q->next;
        }
    }
    while (p != NULL) {
        insert(c, p->coefficient, p->exponent);
        p = p->next;
    }
    while (q != NULL) {
        insert(c, q->coefficient, q->exponent);
        q = q->next;
    }
    return c;
}

int main() {
    Node *a = create();
    Node *b = create();
    insert(a, 3, 2);
    insert(a, 2, 1);
    insert(a, 1, 0);
    insert(b, 4, 3);
    insert(b, 3, 2);
    insert(b, 1, 0);
    printf('a=');
    print(a);
    printf('\nb=');
    print(b);
    Node *c = add(a, b);
    printf('\na+b=');
    print(c);
    return 0;
}

这段代码定义了一个多项式结构体,包括系数和指数,同时定义了创建多项式、插入节点、输出多项式、多项式加法等函数。在主函数中,创建了两个多项式a和b,并分别插入了几个节点,然后进行加法运算并输出结果。

C语言实现一元多项式加法运算

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

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