C语言实现多项式加法:链表实现与内存释放
C语言实现多项式加法:链表实现与内存释放
概述
本文将介绍如何使用C语言实现多项式加法。我们使用链表来存储多项式,并提供详细的代码示例和内存释放方法。
代码实现c#include <stdio.h>#include <stdlib.h>
// 定义链表结构体typedef struct PolyNode { int coef; // 系数 int expn; // 指数 struct PolyNode *next;} PolyNode, *PolyList;
// 创建一个新的链表节点PolyNode *newNode(int coef, int expn) { PolyNode *node = (PolyNode *)malloc(sizeof(PolyNode)); node->coef = coef; node->expn = expn; node->next = NULL; return node;}
// 将两个链表相加PolyList addPoly(PolyList a, PolyList b) { PolyList c = NULL; while (a != NULL && b != NULL) { if (a->expn > b->expn) { PolyNode *temp = a; a = b; b = temp; } PolyNode *node = newNode(a->coef + b->coef, a->expn); if (c == NULL) { c = node; } else { c->next = node; } a = a->next; b = b->next; } while (a != NULL) { PolyNode *node = newNode(a->coef, a->expn); if (c == NULL) { c = node; } else { c->next = node; } a = a->next; } while (b != NULL) { PolyNode *node = newNode(b->coef, b->expn); if (c == NULL) { c = node; } else { c->next = node; } b = b->next; } return c;}
// 打印链表void printPoly(PolyList p) { while (p != NULL) { printf('%dx^%d ', p->coef, p->expn); p = p->next; } printf(' '); // 修正换行符位置}
// 释放链表内存void destroyPoly(PolyList p) { PolyNode* current = p; while (current != NULL) { PolyNode* next = current->next; free(current); current = next; }}
int main() { // 创建两个多项式链表a和b PolyList a = newNode(3, 4); // 3x^4 a->next = newNode(2, 2); // 2x^2 a->next->next = newNode(1, 0); // x^0 a->next->next->next = NULL;
PolyList b = newNode(4, 3); // 4x^3 b->next = newNode(2, 1); // 2x^1 b->next->next = newNode(1, 0); // x^0 b->next->next->next = NULL;
// 计算两个多项式的和 PolyList c = addPoly(a, b);
// 打印结果 printPoly(c);
// 释放内存 destroyPoly(a); destroyPoly(b); destroyPoly(c);
return 0;}
代码解释
- 我们首先定义了一个
PolyNode结构体来表示多项式中的一个节点,它包含系数coef、指数expn和指向下一个节点的指针next。2.newNode函数用于创建一个新的链表节点,并初始化其系数和指数。3.addPoly函数实现了多项式加法的核心逻辑,它遍历两个链表,并将对应指数的系数相加,创建新的节点存储结果。4.printPoly函数用于打印多项式。5.destroyPoly函数用于释放链表所占用的内存,避免内存泄漏。
总结
本文介绍了如何使用C语言实现多项式加法,并提供了详细的代码示例和内存释放方法。希望本文能帮助你理解和应用数据结构与算法。
原文地址: https://www.cveoy.top/t/topic/wV9 著作权归作者所有。请勿转载和采集!