c语言构造两个按指数递增的有序链表,实现两个一元多项式相加
时间: 2024-06-13 16:07:01 浏览: 177
c语言链表实现两个一元递增多项式的相加.zip
以下是C语言实现两个按指数递增的有序链表,实现两个一元多项式相加的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int coef; // 系数
int exp; // 指数
struct node *next; // 下一个节点指针
} Node, *Polynomial;
// 创建一个新节点
Node *createNode(int coef, int exp) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->coef = coef;
newNode->exp = exp;
newNode->next = NULL;
return newNode;
}
// 将一个节点插入到多项式中
void insertNode(Polynomial *p, Node *newNode) {
if (*p == NULL) {
*p = newNode;
return;
}
Node *prev = NULL;
Node *curr = *p;
while (curr != NULL && curr->exp > newNode->exp) {
prev = curr;
curr = curr->next;
}
if (curr != NULL && curr->exp == newNode->exp) {
curr->coef += newNode->coef;
free(newNode);
} else {
if (prev == NULL) {
newNode->next = *p;
*p = newNode;
} else {
newNode->next = curr;
prev->next = newNode;
}
}
}
// 从标准输入中读取多项式
Polynomial readPolynomial() {
Polynomial p = NULL;
int coef, exp;
while (scanf("%d %d", &coef, &exp) == 2) {
Node *newNode = createNode(coef, exp);
insertNode(&p, newNode);
}
return p;
}
// 将多项式输出到标准输出
void printPolynomial(Polynomial p) {
if (p == NULL) {
printf("0 0\n");
return;
}
while (p != NULL) {
printf("%d %d", p->coef, p->exp);
if (p->next != NULL) {
printf(" ");
} else {
printf("\n");
}
p = p->next;
}
}
// 将两个多项式相加
Polynomial addPolynomial(Polynomial p1, Polynomial p2) {
Polynomial p = NULL;
while (p1 != NULL && p2 != NULL) {
if (p1->exp > p2->exp) {
insertNode(&p, createNode(p1->coef, p1->exp));
p1 = p1->next;
} else if (p1->exp < p2->exp) {
insertNode(&p, createNode(p2->coef, p2->exp));
p2 = p2->next;
} else {
int coef = p1->coef + p2->coef;
if (coef != 0) {
insertNode(&p, createNode(coef, p1->exp));
}
p1 = p1->next;
p2 = p2->next;
}
}
while (p1 != NULL) {
insertNode(&p, createNode(p1->coef, p1->exp));
p1 = p1->next;
}
while (p2 != NULL) {
insertNode(&p, createNode(p2->coef, p2->exp));
p2 = p2->next;
}
return p;
}
int main() {
Polynomial p1, p2, p;
printf("请输入第一个多项式的系数和指数,以空格分隔,每个节点一行,以-1 -1结束:\n");
p1 = readPolynomial();
printf("请输入第二个多项式的系数和指数,以空格分隔,每个节点一行,以-1 -1结束:\n");
p2 = readPolynomial();
p = addPolynomial(p1, p2);
printf("相加后的多项式为:\n");
printPolynomial(p);
return 0;
}
```
阅读全文