用单链表实现一元多项式的表示及相加的c语言 具体代码
时间: 2024-02-18 22:04:00 浏览: 120
以下是使用单链表实现一元多项式表示及相加的 C 语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct node {
int coef; // 系数
int exp; // 指数
struct node* next; // 指向下一个节点的指针
} Node;
// 创建链表节点
Node* create_node(int coef, int exp) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->coef = coef;
new_node->exp = exp;
new_node->next = NULL;
return new_node;
}
// 将一元多项式转换为链表表示
Node* poly_to_list(int* coef, int* exp, int n) {
Node *head = create_node(coef[0], exp[0]);
Node *p = head;
for (int i = 1; i < n; i++) {
Node *new_node = create_node(coef[i], exp[i]);
p->next = new_node;
p = new_node;
}
return head;
}
// 打印链表表示的一元多项式
void print_poly(Node* head) {
Node* p = head;
while (p != NULL) {
printf("%dx^%d", p->coef, p->exp);
if (p->next != NULL && p->next->coef > 0) {
printf("+");
}
p = p->next;
}
printf("\n");
}
// 两个一元多项式相加
Node* poly_add(Node* head1, Node* head2) {
Node *p1 = head1, *p2 = head2, *result = NULL, *tail = NULL;
while (p1 != NULL && p2 != NULL) {
if (p1->exp < p2->exp) {
Node *new_node = create_node(p1->coef, p1->exp);
if (result == NULL) {
result = tail = new_node;
} else {
tail->next = new_node;
tail = new_node;
}
p1 = p1->next;
} else if (p1->exp > p2->exp) {
Node *new_node = create_node(p2->coef, p2->exp);
if (result == NULL) {
result = tail = new_node;
} else {
tail->next = new_node;
tail = new_node;
}
p2 = p2->next;
} else { // 指数相同
int coef_sum = p1->coef + p2->coef;
if (coef_sum != 0) {
Node *new_node = create_node(coef_sum, p1->exp);
if (result == NULL) {
result = tail = new_node;
} else {
tail->next = new_node;
tail = new_node;
}
}
p1 = p1->next;
p2 = p2->next;
}
}
// 将未遍历完的链表连接到结果链表的末尾
while (p1 != NULL) {
Node *new_node = create_node(p1->coef, p1->exp);
tail->next = new_node;
tail = new_node;
p1 = p1->next;
}
while (p2 != NULL) {
Node *new_node = create_node(p2->coef, p2->exp);
tail->next = new_node;
tail = new_node;
p2 = p2->next;
}
return result;
}
int main() {
int coef1[] = {3, 2, 5, 0};
int exp1[] = {4, 3, 1, 0};
int n1 = 4;
Node *poly1 = poly_to_list(coef1, exp1, n1);
printf("Poly 1: ");
print_poly(poly1);
int coef2[] = {-2, 2, 3, 1};
int exp2[] = {5, 3, 2, 1};
int n2 = 4;
Node *poly2 = poly_to_list(coef2, exp2, n2);
printf("Poly 2: ");
print_poly(poly2);
Node *result = poly_add(poly1, poly2);
printf("Result: ");
print_poly(result);
return 0;
}
```
以上代码实现了将两个一元多项式转换为链表表示并相加的功能,其中 `poly_to_list` 函数将一元多项式数组转换为链表表示,`print_poly` 函数打印链表表示的一元多项式,`poly_add` 函数实现了两个一元多项式相加,并返回结果链表。
阅读全文