(1) 建立一元多项式单链表时,根据输入值来确定结束构建单链表;(2) 编写一元多项式的相加程序。(3) 要编写多项式单链表的输出函数,以便能验证程序的执行结果。
时间: 2023-05-22 17:06:54 浏览: 95
多项式的相加(用单链表实现)
对于问题一,我们可以先定义一个结构体表示一元多项式,包括指数和系数两个成员变量。然后,我们可以按照输入值逐个插入节点来构建单链表。如果输入的值为0,则表示单链表构建结束。
对于问题二,我们可以遍历两个多项式单链表,将对应项的系数相加后创建新的节点插入结果链表中。同时,如果发现两个多项式单链表中有相同指数的项,需要将它们的系数相加后插入结果链表中。
对于问题三,我们可以简单地遍历多项式单链表,并输出每个节点的指数和系数。
以下是代码示例:
// 定义一元多项式结构体
struct polynomial {
int coefficient; // 系数
int exponent; // 指数
polynomial *next; // 指针域,指向下一个节点
};
// 构建一元多项式单链表
polynomial *create_polynomial() {
int coefficient, exponent;
polynomial *head = new polynomial;
head->next = nullptr;
polynomial *tail = head;
while (true) {
scanf("%d %d", &coefficient, &exponent);
if (exponent == 0) {
break;
}
polynomial *node = new polynomial;
node->coefficient = coefficient;
node->exponent = exponent;
node->next = nullptr;
tail->next = node;
tail = node;
}
return head;
}
// 多项式相加程序
polynomial *add_polynomial(polynomial *p1, polynomial *p2) {
polynomial *result = new polynomial;
result->next = nullptr;
polynomial *tail = result;
while (p1->next != nullptr && p2->next != nullptr) {
if (p1->next->exponent > p2->next->exponent) {
polynomial *node = new polynomial;
node->coefficient = p1->next->coefficient;
node->exponent = p1->next->exponent;
node->next = nullptr;
tail->next = node;
tail = node;
p1 = p1->next;
} else if (p1->next->exponent < p2->next->exponent) {
polynomial *node = new polynomial;
node->coefficient = p2->next->coefficient;
node->exponent = p2->next->exponent;
node->next = nullptr;
tail->next = node;
tail = node;
p2 = p2->next;
} else {
polynomial *node = new polynomial;
node->coefficient = p1->next->coefficient + p2->next->coefficient;
node->exponent = p1->next->exponent;
node->next = nullptr;
tail->next = node;
tail = node;
p1 = p1->next;
p2 = p2->next;
}
}
while (p1->next != nullptr) {
polynomial *node = new polynomial;
node->coefficient = p1->next->coefficient;
node->exponent = p1->next->exponent;
node->next = nullptr;
tail->next = node;
tail = node;
p1 = p1->next;
}
while (p2->next != nullptr) {
polynomial *node = new polynomial;
node->coefficient = p2->next->coefficient;
node->exponent = p2->next->exponent;
node->next = nullptr;
tail->next = node;
tail = node;
p2 = p2->next;
}
return result;
}
// 输出多项式单链表
void print_polynomial(polynomial *p) {
p = p->next;
while (p != nullptr) {
printf("%dx^%d", p->coefficient, p->exponent);
p = p->next;
if (p != nullptr) {
printf(" + ");
}
}
printf("\n");
}
请注意,这只是一个简单的实现,可能不适用于所有情况。在实际项目中,请根据需要进行修改和完善。
阅读全文