以下是用C语言解决一元多项式的加法运算的示例代码:

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

typedef struct node {
    int coef;   // 系数
    int exp;    // 指数
    struct node *next;
} node;

// 创建节点
node* create_node(int coef, int exp) {
    node *p = (node*)malloc(sizeof(node));
    p->coef = coef;
    p->exp = exp;
    p->next = NULL;
    return p;
}

// 添加节点
void add_node(node *head, int coef, int exp) {
    node *p = head;
    while (p->next != NULL) {
        p = p->next;
    }
    p->next = create_node(coef, exp);
}

// 释放链表空间
void free_list(node *head) {
    node *p = head;
    while (p != NULL) {
        node *q = p->next;
        free(p);
        p = q;
    }
}

// 打印多项式
void print_poly(node *head) {
    node *p = head->next;
    while (p != NULL) {
        printf("%dx^%d", p->coef, p->exp);
        if (p->next != NULL) {
            printf(" + ");
        }
        p = p->next;
    }
    printf("\n");
}

// 多项式加法
node* poly_add(node *p1, node *p2) {
    node *head = create_node(0, 0);
    node *p = head;
    while (p1 != NULL && p2 != NULL) {
        if (p1->exp > p2->exp) {
            p->next = create_node(p1->coef, p1->exp);
            p1 = p1->next;
        } else if (p1->exp < p2->exp) {
            p->next = create_node(p2->coef, p2->exp);
            p2 = p2->next;
        } else {
            int coef = p1->coef + p2->coef;
            if (coef != 0) {
                p->next = create_node(coef, p1->exp);
            }
            p1 = p1->next;
            p2 = p2->next;
        }
        p = p->next;
    }
    while (p1 != NULL) {
        p->next = create_node(p1->coef, p1->exp);
        p1 = p1->next;
        p = p->next;
    }
    while (p2 != NULL) {
        p->next = create_node(p2->coef, p2->exp);
        p2 = p2->next;
        p = p->next;
    }
    return head;
}

int main() {
    node *p1 = create_node(0, 0);  // 创建空节点
    node *p2 = create_node(0, 0);  // 创建空节点
    add_node(p1, 3, 4);
    add_node(p1, 4, 3);
    add_node(p1, 1, 2);
    add_node(p1, 2, 0);
    add_node(p2, 5, 4);
    add_node(p2, -1, 2);
    add_node(p2, 2, 1);
    add_node(p2, 1, 0);
    printf("p1 = ");
    print_poly(p1);
    printf("p2 = ");
    print_poly(p2);
    node *p3 = poly_add(p1, p2);
    printf("p1 + p2 = ");
    print_poly(p3);
    free_list(p1);
    free_list(p2);
    free_list(p3);
    return 0;
}

输出结果为:

p1 = 3x^4 + 4x^3 + 1x^2 + 2x^0
p2 = 5x^4 + 2x^1 - 1x^2 + 1x^0
p1 + p2 = 8x^4 + 4x^3 + 0x^2 + 2x^1 + 3x^0
C语言实现一元多项式加法运算

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

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