#include using namespace std;

// 定义单项式结构体 struct Term { int coef; // 系数 int exp; // 指数 Term *next; // 指向下一个单项式的指针 Term(int c, int e) : coef(c), exp(e), next(nullptr) {} };

// 定义多项式类 class Polynomial { private: Term *head; // 头指针 public: Polynomial() : head(nullptr) {} // 构造函数 void insert(int coef, int exp); // 插入单项式 void display(); // 显示多项式 Polynomial operator+(Polynomial &p); // 重载加法运算符 };

void Polynomial::insert(int coef, int exp) { // 如果多项式为空 if (head == nullptr) { head = new Term(coef, exp); return; } // 如果插入的单项式指数大于头结点的指数 if (exp > head->exp) { Term *temp = new Term(coef, exp); temp->next = head; head = temp; return; } // 如果插入的单项式指数等于头结点的指数 if (exp == head->exp) { head->coef += coef; return; } // 如果插入的单项式指数小于头结点的指数 Term *cur = head; while (cur->next != nullptr && exp < cur->next->exp) { cur = cur->next; } if (cur->next == nullptr) { cur->next = new Term(coef, exp); return; } if (exp == cur->next->exp) { cur->next->coef += coef; return; } Term *temp = new Term(coef, exp); temp->next = cur->next; cur->next = temp; }

void Polynomial::display() { if (head == nullptr) { cout << "0" << endl; return; } Term *cur = head; cout << cur->coef << "x^" << cur->exp; cur = cur->next; while (cur != nullptr) { if (cur->coef > 0) { cout << " + " << cur->coef << "x^" << cur->exp; } else { cout << " - " << -cur->coef << "x^" << cur->exp; } cur = cur->next; } cout << endl; }

Polynomial Polynomial::operator+(Polynomial &p) { Polynomial res; Term *cur1 = head, *cur2 = p.head; while (cur1 != nullptr && cur2 != nullptr) { if (cur1->exp > cur2->exp) { res.insert(cur1->coef, cur1->exp); cur1 = cur1->next; } else if (cur1->exp < cur2->exp) { res.insert(cur2->coef, cur2->exp); cur2 = cur2->next; } else { int coef = cur1->coef + cur2->coef; if (coef != 0) { res.insert(coef, cur1->exp); } cur1 = cur1->next; cur2 = cur2->next; } } while (cur1 != nullptr) { res.insert(cur1->coef, cur1->exp); cur1 = cur1->next; } while (cur2 != nullptr) { res.insert(cur2->coef, cur2->exp); cur2 = cur2->next; } return res; }

int main() { Polynomial p, q; int n, coef, exp; cout << "请输入第一个多项式的项数:"; cin >> n; cout << "请依次输入" << n << "个单项式(系数和指数):" << endl; for (int i = 0; i < n; i++) { cin >> coef >> exp; p.insert(coef, exp); } cout << "请输入第二个多项式的项数:"; cin >> n; cout << "请依次输入" << n << "个单项式(系数和指数):" << endl; for (int i = 0; i < n; i++) { cin >> coef >> exp; q.insert(coef, exp); } cout << "第一个多项式:"; p.display(); cout << "第二个多项式:"; q.display(); Polynomial r = p + q; cout << "它们的和为:"; r.display(); return 0; }

用c++写一段代码把任意给定的两个一元多项式Px Qx 输入计算机计算它们的和并输出计算结果。一元多项式可以用单链表表示

原文地址: https://www.cveoy.top/t/topic/bJnx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录