利用有序单链表实现两个多项式相加
时间: 2023-05-15 10:07:52 浏览: 145
可以按照以下步骤实现:
1. 定义一个有序单链表结构体,包含两个成员变量:系数和指数。
2. 分别输入两个多项式的系数和指数,将它们按照指数从大到小的顺序插入到有序单链表中。
3. 定义一个新的有序单链表,用于存储相加后的多项式。
4. 遍历两个有序单链表,将相同指数的项相加,将结果插入到新的有序单链表中。
5. 如果有一个有序单链表已经遍历完了,将另一个有序单链表中剩余的项插入到新的有序单链表中。
6. 输出新的有序单链表中的项,即为相加后的多项式。
以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义有序单链表结构体
typedef struct node {
int coef; // 系数
int exp; // 指数
struct node *next;
} Node;
// 插入节点到有序单链表中
void insert(Node **head, int coef, int exp) {
Node *new_node = (Node *)malloc(sizeof(Node));
new_node->coef = coef;
new_node->exp = exp;
new_node->next = NULL;
if (*head == NULL || exp > (*head)->exp) {
new_node->next = *head;
*head = new_node;
} else {
Node *cur = *head;
while (cur->next != NULL && exp < cur->next->exp) {
cur = cur->next;
}
new_node->next = cur->next;
cur->next = new_node;
}
}
// 释放有序单链表的内存
void free_list(Node *head) {
Node *cur = head;
while (cur != NULL) {
Node *temp = cur;
cur = cur->next;
free(temp);
}
}
// 打印有序单链表中的项
void print_list(Node *head) {
Node *cur = head;
while (cur != NULL) {
printf("%dx^%d ", cur->coef, cur->exp);
cur = cur->next;
}
printf("\n");
}
// 两个多项式相加
Node *add_poly(Node *poly1, Node *poly2) {
Node *result = NULL;
while (poly1 != NULL && poly2 != NULL) {
if (poly1->exp > poly2->exp) {
insert(&result, poly1->coef, poly1->exp);
poly1 = poly1->next;
} else if (poly1->exp < poly2->exp) {
insert(&result, poly2->coef, poly2->exp);
poly2 = poly2->next;
} else {
int sum = poly1->coef + poly2->coef;
if (sum != 0) {
insert(&result, sum, poly1->exp);
}
poly1 = poly1->next;
poly2 = poly2->next;
}
}
while (poly1 != NULL) {
insert(&result, poly1->coef, poly1->exp);
poly1 = poly1->next;
}
while (poly2 != NULL) {
insert(&result, poly2->coef, poly2->exp);
poly2 = poly2->next;
}
return result;
}
int main() {
// 输入第一个多项式
printf("Enter the first polynomial:\n");
Node *poly1 = NULL;
int coef, exp;
do {
printf("Enter coefficient and exponent (enter 0 0 to stop): ");
scanf("%d %d", &coef, &exp);
if (coef != 0) {
insert(&poly1, coef, exp);
}
} while (coef != 0 || exp != 0);
// 输入第二个多项式
printf("Enter the second polynomial:\n");
Node *poly2 = NULL;
do {
printf("Enter coefficient and exponent (enter 0 0 to stop): ");
scanf("%d %d", &coef, &exp);
if (coef != 0) {
insert(&poly2, coef, exp);
}
} while (coef != 0 || exp != 0);
// 输出两个多项式
printf("First polynomial: ");
print_list(poly1);
printf("Second polynomial: ");
print_list(poly2);
// 计算相加后的多项式
Node *result = add_poly(poly1, poly2);
// 输出相加后的多项式
printf("Result: ");
print_list(result);
// 释放内存
free_list(poly1);
free_list(poly2);
free_list(result);
return 0;
}
```
如果您有任何问题,请随时问我。