思路:
1.创建一个结点结构
(1)系数域
(2)指数域
(3)指针域
2.创建一个多项式的类
(1)定义头结点和表长(len)
(2)函数
<1>初始化函数
<2>插入函数
<3>输入函数
<4>输出函数
<5>相加函数(精华)
对于相加函数,我的做法是传入两个多项式类,再对它进行累加
代码如下:
#include<iostream> using namespace std; //定义结点 struct Node { int coef;//系数 int exp;//指数 Node* next;//指针 }; //定义类 class Polynomial { public: Node* head; int len; //插入pos:1-(n+1) void Insert(int pos, int coef, int exp) { Node* p = head; //移动 for (int i = 1; i < pos; i++) { p = p->next; } //分配结点,赋值 Node* s = new Node; s->coef = coef; s->exp = exp; //插入结点 s->next = p->next; p->next = s; //长度加一 len++; } //初始化 void Init() { head = new Node; head->next = NULL; len = 0; } //输出 void Output() { Node* p; if (len == 0) { cout << "该多项式为空" << endl; } else { cout << "该多项式为:" << endl; p = head->next; for (int i = 0; i < len; i++) { cout << "<" << p->coef << "," << p->exp << ">||"; p = p->next; } cout << endl; } } //输入函数 void Input() { int number,coef,exp; cout << "请输入多项式的项数:"; cin >> number; for (int i = 0; i < number; i++) { cout << "请输入第" << (i + 1) << "项的系数:" << endl; cin >> coef; cout << "请输入第" << (i + 1) << "项的指数:" << endl; cin >> exp; //插入 Insert(len+1, coef, exp); } } //相加,传入两个Polynomial的链表 void Add(Polynomial x, Polynomial y) { Node* pa = x.head->next;//pa指针指向a的第一个结点 Node* pb = y.head->next;//pb指针指向b的第一个结点 while ((pa != NULL) && (pb != NULL)) { //第一种情况 if (pa->exp < pb->exp) { Insert(len + 1, pa->coef, pa->exp); pa = pa->next;//后移一格 } //第二种情况 else if (pa->exp > pb->exp) { Insert(len + 1, pb->coef, pb->exp); pb = pb->next;//后移一格 } else if (pa->exp == pb->exp) { int temp = pa->coef + pb->coef; if (temp!=0) {//如果相加不为零 Insert(len + 1, temp, pa->exp); } pa = pa->next;//后移一格 pb = pb->next;//后移一格 } } pa = (pa == NULL) ? pb : pa; while (pa != NULL) { Insert(len + 1, pa->coef, pa->exp); pa = pa->next;//后移 } } }; int main() { //定义三个类 Polynomial a; Polynomial b; Polynomial c; //对三个类进行初始化 a.Init(); b.Init(); c.Init(); //先输入a和b a.Input(); b.Input(); //多项式相加 c.Add(a, b); //输出abc a.Output(); b.Output(); c.Output(); }