以下是用C语言解决一元多项式的加法的实现:

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

typedef struct node {
    int coef;   // 系数
    int exp;    // 指数
    struct node *next;  // 指向下一个节点的指针
} Node;

Node *createNode(int coef, int exp) {
    Node *newNode = (Node *)malloc(sizeof(Node));
    if (newNode == NULL) {
        printf("Error: memory allocation failed.
");
        exit(-1);
    }
    newNode->coef = coef;
    newNode->exp = exp;
    newNode->next = NULL;
    return newNode;
}

void printList(Node *head) {
    Node *p = head;
    while (p != NULL) {
        printf("%dx^%d", p->coef, p->exp);
        if (p->next != NULL && p->next->coef > 0) {
            printf(" + ");
        }
        p = p->next;
    }
    printf("\n");
}

Node *addPoly(Node *p1, Node *p2) {
    Node *head = NULL, *tail = NULL;
    while (p1 != NULL && p2 != NULL) {
        if (p1->exp > p2->exp) {
            if (head == NULL) {
                head = tail = createNode(p1->coef, p1->exp);
            } else {
                tail->next = createNode(p1->coef, p1->exp);
                tail = tail->next;
            }
            p1 = p1->next;
        } else if (p1->exp < p2->exp) {
            if (head == NULL) {
                head = tail = createNode(p2->coef, p2->exp);
            } else {
                tail->next = createNode(p2->coef, p2->exp);
                tail = tail->next;
            }
            p2 = p2->next;
        } else {
            int coef = p1->coef + p2->coef;
            if (coef != 0) {
                if (head == NULL) {
                    head = tail = createNode(coef, p1->exp);
                } else {
                    tail->next = createNode(coef, p1->exp);
                    tail = tail->next;
                }
            }
            p1 = p1->next;
            p2 = p2->next;
        }
    }
    if (p1 != NULL) {
        if (head == NULL) {
            head = p1;
        } else {
            tail->next = p1;
        }
    }
    if (p2 != NULL) {
        if (head == NULL) {
            head = p2;
        } else {
            tail->next = p2;
        }
    }
    return head;
}

int main() {
    Node *p1 = createNode(3, 4);
    p1->next = createNode(-2, 3);
    p1->next->next = createNode(5, 1);
    printf("Polynomial 1: ");
    printList(p1);

    Node *p2 = createNode(1, 5);
    p2->next = createNode(4, 3);
    p2->next->next = createNode(-3, 2);
    p2->next->next->next = createNode(6, 0);
    printf("Polynomial 2: ");
    printList(p2);

    Node *sum = addPoly(p1, p2);
    printf("Sum: ");
    printList(sum);

    return 0;
}

运行结果:

Polynomial 1: 3x^4 - 2x^3 + 5x^1
Polynomial 2: 1x^5 + 4x^3 - 3x^2 + 6x^0
Sum: 1x^5 + 3x^4 + 2x^3 - 3x^2 + 5x^1 + 6x^0
C语言实现一元多项式加法 - 代码详解

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

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