c语言 编写一个程序实现两个一元多项式相加的运算
时间: 2024-05-02 10:21:29 浏览: 137
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int coef; //系数
int exp; //指数
struct Node *next;
}Node, *Polynomial;
//创建一元多项式
Polynomial createPolynomial(int n){
Polynomial P, rear, s;
P = (Polynomial)malloc(sizeof(Node));
P->next = NULL;
rear = P;
int i;
for(i = 0; i < n; i++){
s = (Polynomial)malloc(sizeof(Node));
scanf("%d %d", &s->coef, &s->exp);
if(s->coef != 0){
rear->next = s;
rear = s;
}else{
free(s);
}
}
rear->next = NULL;
return P;
}
//打印一元多项式
void printPolynomial(Polynomial P){
Polynomial p = P->next;
int flag = 0;
if(!p){
printf("0 0\n");
}else{
while(p){
if(!flag){
flag = 1;
}else{
printf(" ");
}
printf("%d %d", p->coef, p->exp);
p = p->next;
}
}
printf("\n");
}
//一元多项式相加
Polynomial addPolynomial(Polynomial P1, Polynomial P2){
Polynomial P, rear, t1, t2, s;
t1 = P1->next;
t2 = P2->next;
P = (Polynomial)malloc(sizeof(Node));
P->next = NULL;
rear = P;
while(t1 && t2){
if(t1->exp == t2->exp){
int sum = t1->coef + t2->coef;
if(sum != 0){
s = (Polynomial)malloc(sizeof(Node));
s->coef = sum;
s->exp = t1->exp;
rear->next = s;
rear = s;
}
t1 = t1->next;
t2 = t2->next;
}else if(t1->exp > t2->exp){
s = (Polynomial)malloc(sizeof(Node));
s->coef = t1->coef;
s->exp = t1->exp;
rear->next = s;
rear = s;
t1 = t1->next;
}else{
s = (Polynomial)malloc(sizeof(Node));
s->coef = t2->coef;
s->exp = t2->exp;
rear->next = s;
rear = s;
t2 = t2->next;
}
}
while(t1){
s = (Polynomial)malloc(sizeof(Node));
s->coef = t1->coef;
s->exp = t1->exp;
rear->next = s;
rear = s;
t1 = t1->next;
}
while(t2){
s = (Polynomial)malloc(sizeof(Node));
s->coef = t2->coef;
s->exp = t2->exp;
rear->next = s;
rear = s;
t2 = t2->next;
}
rear->next = NULL;
return P;
}
int main(){
int n, m;
Polynomial P1, P2, P3;
scanf("%d", &n);
P1 = createPolynomial(n);
scanf("%d", &m);
P2 = createPolynomial(m);
P3 = addPolynomial(P1, P2);
printPolynomial(P3);
return 0;
}
```
使用方法:
输入第一个一元多项式的项数 n,接下来 n 行,每行输入一个系数和一个指数,以空格分隔。
输入第二个一元多项式的项数 m,接下来 m 行,每行输入一个系数和一个指数,以空格分隔。
程序将输出两个一元多项式相加的结果。
阅读全文