自行为普通一元多项式设计存储结构,实现如下功能:\n\n① 输入:从键盘输入一元多项式的各项系数,创建一元多项式;\n\n② 输出:按给定格式输出一元多项式;(例如:3*x^2-x+10)\n\n③ 多项式加法:
时间: 2023-04-26 20:03:42 浏览: 92
数据结构课程设计一元多项式.doc
可以使用链表来设计一元多项式的存储结构,每个节点存储一个项的系数和指数。具体实现如下:
1. 定义一个结构体,包含两个成员变量:系数和指数。
```
struct PolyNode {
int coef; // 系数
int exp; // 指数
PolyNode* next; // 指向下一个节点的指针
};
```
2. 定义一个链表类,包含头节点和尾节点。
```
class Polynomial {
public:
Polynomial(); // 构造函数,初始化头节点和尾节点
~Polynomial(); // 析构函数,释放链表内存
void input(); // 输入多项式
void output(); // 输出多项式
Polynomial add(Polynomial& b); // 多项式加法
private:
PolyNode* head; // 头节点
PolyNode* tail; // 尾节点
};
```
3. 实现链表类的各个方法。
构造函数:
```
Polynomial::Polynomial() {
head = new PolyNode;
tail = head;
head->next = nullptr;
}
```
析构函数:
```
Polynomial::~Polynomial() {
PolyNode* p = head;
while (p != nullptr) {
PolyNode* q = p->next;
delete p;
p = q;
}
}
```
输入多项式:
```
void Polynomial::input() {
int n;
cout << "请输入多项式的项数:";
cin >> n;
for (int i = 0; i < n; i++) {
int coef, exp;
cout << "请输入第" << i+1 << "项的系数和指数:";
cin >> coef >> exp;
PolyNode* node = new PolyNode;
node->coef = coef;
node->exp = exp;
node->next = nullptr;
tail->next = node;
tail = node;
}
}
```
输出多项式:
```
void Polynomial::output() {
PolyNode* p = head->next;
bool first = true;
while (p != nullptr) {
if (p->coef != 0) {
if (!first && p->coef > 0) {
cout << "+";
}
if (p->coef != 1 && p->coef != -1) {
cout << p->coef;
} else if (p->coef == -1) {
cout << "-";
}
if (p->exp == 0) {
cout << p->coef;
} else if (p->exp == 1) {
cout << "x";
} else {
cout << "x^" << p->exp;
}
first = false;
}
p = p->next;
}
if (first) {
cout << "0";
}
cout << endl;
}
```
多项式加法:
```
Polynomial Polynomial::add(Polynomial& b) {
Polynomial c;
PolyNode* p = head->next;
PolyNode* q = b.head->next;
while (p != nullptr && q != nullptr) {
if (p->exp == q->exp) {
int coef = p->coef + q->coef;
if (coef != 0) {
PolyNode* node = new PolyNode;
node->coef = coef;
node->exp = p->exp;
node->next = nullptr;
c.tail->next = node;
c.tail = node;
}
p = p->next;
q = q->next;
} else if (p->exp > q->exp) {
PolyNode* node = new PolyNode;
node->coef = p->coef;
node->exp = p->exp;
node->next = nullptr;
c.tail->next = node;
c.tail = node;
p = p->next;
} else {
PolyNode* node = new PolyNode;
node->coef = q->coef;
node->exp = q->exp;
node->next = nullptr;
c.tail->next = node;
c.tail = node;
q = q->next;
}
}
while (p != nullptr) {
PolyNode* node = new PolyNode;
node->coef = p->coef;
node->exp = p->exp;
node->next = nullptr;
c.tail->next = node;
c.tail = node;
p = p->next;
}
while (q != nullptr) {
PolyNode* node = new PolyNode;
node->coef = q->coef;
node->exp = q->exp;
node->next = nullptr;
c.tail->next = node;
c.tail = node;
q = q->next;
}
return c;
}
```
以上就是一元多项式的存储结构和实现方法。
阅读全文