链表实现多项式乘法

使用链表的基本操作实现多项式乘法是一个经典的编程任务。以下是用C语言编写的实现步骤:

1. 定义节点结构:创建一个表示多项式项的节点结构体,包含系数和指数,以及指向下一个节点的指针。

2. 创建链表:初始化两个链表分别表示两个多项式,并按指数大小排序。

3. 实现乘法运算:遍历两个链表,对每一对节点的系数和指数进行乘法运算,将结果插入到结果链表中,按指数大小合并同类项。

4. 输出结果:遍历结果链表,输出最终的多项式乘积。

示例代码如下:

#include 
#include 

typedef struct Node {
    int coeff;
    int exp;
    struct Node* next;
} Node;

Node* createNode(int coeff, int exp) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->coeff = coeff;
    newNode->exp = exp;
    newNode->next = NULL;
    return newNode;
}

Node* insertNode(Node* head, int coeff, int exp) {
    Node* newNode = createNode(coeff, exp);
    if (!head || head->exp < exp>next = head;
        return newNode;
    }
    Node* temp = head;
    while (temp->next && temp->next->exp >= exp) {
        temp = temp->next;
    }
    newNode->next = temp->next;
    temp->next = newNode;
    return head;
}

Node* multiplyPoly(Node* poly1, Node* poly2) {
    Node* result = NULL;
    Node* temp1 = poly1;
    while (temp1) {
        Node* temp2 = poly2;
        while (temp2) {
            int coeff = temp1->coeff * temp2->coeff;
            int exp = temp1->exp + temp2->exp;
            result = insertNode(result, coeff, exp);
            temp2 = temp2->next;
        }
        temp1 = temp1->next;
    }
    return result;
}

void printPoly(Node* head) {
    Node* temp = head;
    while (temp) {
        printf("%dx^%d", temp->coeff, temp->exp);
        if (temp->next) {
            printf(" + ");
        }
        temp = temp->next;
    }
    printf("
");
}

int main() {
    Node* poly1 = NULL;
    Node* poly2 = NULL;

    poly1 = insertNode(poly1, 3, 2);
    poly1 = insertNode(poly1, 5, 1);

    poly2 = insertNode(poly2, 4, 1);
    poly2 = insertNode(poly2, 2, 0);

    Node* result = multiplyPoly(poly1, poly2);

    printf("Resultant polynomial: ");
    printPoly(result);

    return 0;
}

此代码展示了如何通过链表实现多项式的乘法。

c 文件大小:5.01KB