用c语言实现一元多项式的加和
时间: 2023-11-18 17:05:50 浏览: 30
#include<stdio.h>
#include<stdlib.h>
typedef struct PolyNode* PtrToPolyNode;
struct PolyNode{
int coef;
int expon;
PtrToPolyNode next;
};
typedef PtrToPolyNode Polynomial;
Polynomial ReadPoly();
void Attach(int c, int e, Polynomial* pRear);
Polynomial Add(Polynomial P1, Polynomial P2);
void PrintPoly(Polynomial P);
int main()
{
Polynomial P1, P2, PP;
P1 = ReadPoly();
P2 = ReadPoly();
PP = Add(P1, P2);
PrintPoly(PP);
return 0;
}
Polynomial ReadPoly()
{
Polynomial P, Rear, t;
int N, c, e;
P = (Polynomial)malloc(sizeof(struct PolyNode));
P->next = NULL;
Rear = P;
scanf("%d", &N);
while(N--){
scanf("%d %d", &c, &e);
Attach(c, e, &Rear);
}
t = P;
P = P->next;
free(t);
return P;
}
void Attach(int c, int e, Polynomial* pRear)
{
Polynomial P;
P = (Polynomial)malloc(sizeof(struct PolyNode));
P->coef = c;
P->expon = e;
P->next = NULL;
(*pRear)->next = P;
*pRear = P;
}
Polynomial Add(Polynomial P1, Polynomial P2)
{
Polynomial t1, t2, P, Rear, t;
int sum;
t1 = P1;
t2 = P2;
P = (Polynomial)malloc(sizeof(struct PolyNode));
P->next = NULL;
Rear = P;
while(t1 && t2){
if(t1->expon == t2->expon){
sum = t1->coef + t2->coef;
if(sum)
Attach(sum, t1->expon, &Rear);
t1 = t1->next;
t2 = t2->next;
}
else if(t1->expon > t2->expon){
Attach(t1->coef, t1->expon, &Rear);
t1 = t1->next;
}
else{
Attach(t2->coef, t2->expon, &Rear);
t2 = t2->next;
}
}
while(t1){
Attach(t1->coef, t1->expon, &Rear);
t1 = t1->next;
}
while(t2){
Attach(t2->coef, t2->expon, &Rear);
t2 = t2->next;
}
t = P;
P = P->next;
free(t);
return P;
}
void PrintPoly(Polynomial P)
{
int flag = 0;
if(!P){
printf("0 0\n");
return;
}
while(P){
if(!flag)
flag = 1;
else
printf(" ");
printf("%d %d", P->coef, P->expon);
P = P->next;
}
printf("\n");
}
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)