线性表应用2——一元多项式加法运算,要求采用链式存储结构实现,其中对链表的建立、合并和结果输出用自定义函数完成。
时间: 2024-09-23 09:05:07 浏览: 94
要使用链式存储结构(如单链表)实现一元多项式的加法运算,你需要创建三个主要的部分:节点定义、链表操作函数以及加法算法。
首先,我们定义一个节点结构体,它包含系数和指数两个字段:
```c
typedef struct {
double coefficient; // 系数
int exponent; // 指数
} Term;
// 创建新节点的函数
Term* create_term(double coeff, int exp) {
Term* new_node = (Term*)malloc(sizeof(Term));
if (new_node) {
new_node->coefficient = coeff;
new_node->exponent = exp;
}
return new_node;
}
```
接下来,我们需要链表操作函数,用于插入节点、合并链表以及输出链表:
```c
// 插入节点到链表尾部的函数
void insert_to_list(Term** head, Term* term) {
if (*head == NULL) {
*head = term;
} else {
Term* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = term;
}
}
// 合并两个多项式链表的函数
Term* add_polynomials(Term** poly1, Term** poly2) {
Term* result_head = NULL;
Term* current1 = *poly1, *current2 = *poly2;
while (current1 != NULL && current2 != NULL) {
double sum_coeff = current1->coefficient + current2->coefficient;
int max_exp = MAX(current1->exponent, current2->exponent);
Term* merged_term = create_term(sum_coeff, max_exp);
if (result_head == NULL) {
result_head = merged_term;
} else {
Term* temp = result_head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = merged_term;
}
if (current1->coefficient != 0 || current2->coefficient != 0) { // 防止进位丢失
current1 = current1->exponent < current2->exponent ? current2 : current1;
current2 = current1->exponent < current2->exponent ? current1 : current2;
}
}
// 如果其中一个链表未结束,则添加剩余项
if (current1 != NULL) {
Term* temp = result_head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = current1;
} else if (current2 != NULL) {
Term* temp = result_head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = current2;
}
return result_head;
}
// 输出链表函数
void print_polynomial(Term* head) {
Term* current = head;
while (current != NULL) {
printf("%.2lfx^%d ", current->coefficient, current->exponent);
current = current->next;
}
printf("\n");
}
```
现在你可以按照以下步骤使用这些函数:
1. 建立两个多项式的链表,比如 `poly1` 和 `poly2`。
2. 使用 `add_polynomials(&poly1, &poly2)` 函数计算它们的和。
3. 最后,调用 `print_polynomial(result_head)` 来输出结果。
阅读全文