一题数据结构题,请高手帮忙解决啊..
- 提问者网友:我是女神我骄傲
- 2021-07-20 00:24
例如两个多项式3x^2+6x+3和3x^3-x^2-6x+10,他们之间进行加运算,则得到新的多项式为3x^3+2x^2+13。
存储方式可以任意选择数组或者链表。键盘的输入方式以及输出方式自定。
- 五星知识达人网友:从此江山别
- 2021-07-20 01:53
- 1楼网友:七十二街
- 2021-07-20 05:51
曾经编过一个只有相加和相减的要不要?要的话联系。
- 2楼网友:轻雾山林
- 2021-07-20 04:34
- 3楼网友:山河有幸埋战骨
- 2021-07-20 03:29
// 多项式相加 #include <iostream.h> #include <stdlib.h>
//节点定义 struct NodeType{ float coef; int exp; struct NodeType *next; };
// 多项式--初始化用 struct Poly_Item{ float coef; int exp; };
// 函数原型 bool Init(NodeType *&head); bool InsertAfter(NodeType *p, float c, int e); NodeType *Add_Poly(NodeType *a, NodeType *b); NodeType * Creat_Poly(Poly_Item v[], int n); void Print_Poly(char *s, NodeType *a);
// 初始化 bool Init(NodeType *&head) { if((head = new NodeType) == NULL) return false; head -> next = head; return true; }
// 插入一个节点 bool InsertAfter(NodeType *p, float c, int e) { NodeType *q; if((q = new NodeType) == NULL) return false; q -> coef = c; q -> exp = e; q -> next = p -> next; p -> next = q; return true; }
// 多项式相加 NodeType *Add_Poly(NodeType *a, NodeType *b) { float v; NodeType *c,*pc, *pa = a->next, *pb = b->next; Init(c); pc = c; while(pa != a && pb != b){ if(pa -> exp == pb -> exp){ if((v = pa -> coef + pb -> coef) != 0){ InsertAfter(pc, v, pa -> exp); pc = pc -> next; } pa = pa -> next; pb = pb -> next; }else if(pa -> exp < pb -> exp){ InsertAfter(pc, pa -> coef, pa -> exp); pc = pc -> next; pa = pa -> next; }else{ InsertAfter(pc, pb -> coef, pb -> exp); pc = pc -> next; pb = pb -> next; } } while(pa != a){ InsertAfter(pc, pa -> coef, pa -> exp); pc = pc -> next; pa = pa -> next; } while(pb != b){ InsertAfter(pc, pb -> coef, pb -> exp); pc = pc -> next; pb = pb -> next; } return c; }
// 建立多项式的循环单链表 NodeType * Creat_Poly(Poly_Item v[], int n) { NodeType *p; int j;
Init(p); for(j = 0; j < n; j++){ InsertAfter(p, v[j].coef, v[j].exp); p = p -> next; } return p -> next; }
// 打印函数 void Print_Poly(char *s, NodeType *a) { NodeType *p = a -> next;
cout << s; if(p != a){ cout << p -> coef << 'X' << '^' << p -> exp; p = p -> next; while(p != a){ if(p -> coef > 0) cout << '+'; cout << p -> coef << 'X' << '^' << p -> exp; p = p -> next; } } cout << endl; }
void main(void) { NodeType *a, *b, *c; Poly_Item v1[] = {{7, 0}, {-8, 1}, {9, 8}, {5, 17}}, v2[] = {{8, 1}, {22, 7}, {-6, 8}, {4, 12}, {-7, 15}};
a = Creat_Poly(v1, 4); b = Creat_Poly(v2, 5); Print_Poly("Poly_A =", a); Print_Poly("Poly_B =", b); c = Add_Poly(a, b); Print_Poly("Poly_c =", c); }