一元多项式加法运算的C语言实现
时间: 2024-05-04 18:12:20 浏览: 140
好的,以下是一元多项式加法运算的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int coef; // 系数
int expn; // 指数
struct node *next;
} Node, *Polynomial;
void CreatePolyn(Polynomial *p, int m) {
*p = (Polynomial)malloc(sizeof(Node));
(*p)->next = NULL;
Node *tail = *p;
for (int i = 0; i < m; i++) {
Node *node = (Node*)malloc(sizeof(Node));
scanf("%d %d", &node->coef, &node->expn);
tail->next = node; tail = node;
}
tail->next = NULL;
}
void PrintPolyn(Polynomial p) {
Node *node = p->next;
while (node) {
printf("%d %d ", node->coef, node->expn);
node = node->next;
}
printf("\n");
}
void AddPolyn(Polynomial *pa, Polynomial *pb) {
Node *a = (*pa)->next, *b = (*pb)->next, *pre = *pa;
while (a && b) {
if (a->expn == b->expn) {
a->coef += b->coef;
if (a->coef == 0) {
pre->next = a->next;
free(a);
a = pre->next;
} else {
pre = a;
a = a->next;
}
b = b->next;
} else if (a->expn < b->expn) {
pre->next = b;
b = b->next;
pre->next->next = a;
pre = pre->next;
} else {
pre = a;
a = a->next;
}
}
if (b) {
pre->next = b;
}
free(*pb);
}
int main() {
Polynomial pa, pb;
int m, n;
scanf("%d", &m);
CreatePolyn(&pa, m);
scanf("%d", &n);
CreatePolyn(&pb, n);
AddPolyn(&pa, &pb);
PrintPolyn(pa);
return 0;
}
```
阅读全文