利用链表实现两个稀疏多项式相加。
代码
#include <iostream>
using namespace std;// 定义多项式项结构体
typedef struct {int x; // 系数int y; // 指数
} Elemtype;// 定义链表节点结构体
typedef struct Node {Elemtype data;struct Node* next;
} *LinkList, Node;// 创建多项式链表,按照乱序输入顺序输出
void Great_LinkList(LinkList& L) {int n;Node* s, * pre, * p;cout << "请输入多项式的项数:";cin >> n;L = new Node; // 建立一个带头结点的单链表L->next = NULL;for (int i = 1; i <= n; i++) {s = new Node;cout << "请输入第" << i << "项的系数和指数:";cin >> s->data.x >> s->data.y;//注意此步在for循环内部,每次都需要从头开始找pre = L; p = L->next;while (p && p->data.y < s->data.y) {pre = p;p = p->next;}s->next = p;pre->next = s;}
}// 显示多项式
void Show(LinkList L) {Node* p;p = L->next;cout << "f(x)=";while (p) {if (p->data.x != 0) {if (p->data.x > 0) {if (p->data.y)cout << "+" << p->data.x << "x^" << p->data.y;elsecout << p->data.x;}else {if (p->data.y)cout << p->data.x << "x^" << p->data.y;elsecout << p->data.x;}}p = p->next;}
}// 多项式相加
void Add_List(LinkList& LA, LinkList& LB) {Node* pa, * pb, * pc, * r;pc = LA; // 复制 LA 链表作为 LC 的初始值pa = LA->next; pb = LB->next;while (pa && pb) {if (pa->data.y == pb->data.y) {pa->data.x += pb->data.x; // 相加系数if (pa->data.x != 0) { // 系数相加不为 0pc->next = pa;pc = pa;pa = pa->next;r = pb; pb = pb->next; delete r; // 跳过当前项}else { // 系数为 0,删除当前项r = pa; pa = pa->next; delete r;r = pb; pb = pb->next; delete r;}}else if (pa->data.y < pb->data.y) {pc->next = pa;pc = pa;pa = pa->next;}else {pc->next = pb;pc = pb;pb = pb->next;}}pc->next = pa ? pa : pb; // 连接剩余项Show(LA);}int main() {int n;LinkList L1, L2, LC;cout << "开始创建第一个多项式:" << endl;Great_LinkList(L1); // 创建第一个多项式cout << "开始创建第二个多项式:" << endl;Great_LinkList(L2); // 创建第二个多项式cout << "你创建的第一个多项式为:";Show(L1);cout << endl;cout << "你创建的第二个多项式为:";Show(L2);cout << endl;cout << "两个多项式相加的结果为:";Add_List(L1, L2);cout << endl;return 0;
}
void Add_List(LinkList & LA, LinkList & LB, LinkList & LC) {Node* pa, * pb, * pc;LC = LA, detete LB;pa = LA->next; pb = LB->next;pc = LC->next;while (pa && pb) {if (pa->data.y == pb->data.y) {sum = pa->data.y + pb->data.y;if (sum) { //系数和不为0pa->data.y = sum;pc->next = pa;pc = pa;pa = pa->next;r = pb; pb = pb->next; delete pb;}else { //系数相加为0r = pa; pa = pa->next; delete pa;r = pb; pb = pb->next; delete pb;}}else if (pa->data.y < pb->data.y) {pc->next = pa;pc = pa;pa = pa->next;}else {pc->next = pb;pc = pb;pb = pb->next;}pc->next = pa ? pa : pb;Show(LC);
运行结果
下面是我最初写的多项式相加的代码,传了一个LC过来,最后运行出现了错误。
void Add_List(LinkList & LA, LinkList & LB, LinkList & LC) {Node* pa, * pb, * pc;LC = LA, detete LB;pa = LA->next; pb = LB->next;pc = LC->next;while (pa && pb) {if (pa->data.y == pb->data.y) {sum = pa->data.y + pb->data.y;if (sum) { //系数和不为0pa->data.y = sum;pc->next = pa;pc = pa;pa = pa->next;r = pb; pb = pb->next; delete pb;}else { //系数相加为0r = pa; pa = pa->next; delete pa;r = pb; pb = pb->next; delete pb;}}else if (pa->data.y < pb->data.y) {pc->next = pa;pc = pa;pa = pa->next;}else {pc->next = pb;pc = pb;pb = pb->next;}pc->next = pa ? pa : pb;Show(LC);