#include<stdio.h>
#include<stdlib.h>
//Polynomial
//coef 系数
//expon 指数
struct PolyNode
{
int coef;
int expon;
struct PolyNode *link;
};
typedef struct PolyNode *Polynomial;
//函数声明
void Attach(int c, int e, Polynomial *pRear);
int Compare(int a, int b);
Polynomial PolyAdd(Polynomial P1, Polynomial P2)
{
Polynomial front, rear, temp;
rear = (Polynomial)malloc( sizeof(struct PolyNode) );
front = rear;
//rear->link = NULL;
int sum;
while(P1 && P2)
{
switch (Compare(P1->expon,P2->expon))
{
case 1:
//如果P1的指数大,把P1添加到队列尾部
Attach(P1->coef,P1->expon,&rear);
P1 = P1->link;
break;
case -1:
//如果P2的指数大,把P2添加到队列尾部
Attach(P2->coef,P2->expon,&rear);
P2 = P2->link;
break;
case 0:
//如果指数相等,判断系数和是否为0,不为0相加后添加到队列尾
sum = P1->coef + P2->coef;
if(sum)
{
Attach(sum,P1->expon,&rear);
P1 = P1->link;
P2 = P2->link;
}
break;
}
}
//推出循环后不是P1为空,就是P2为空
for(;P1;P1 = P1->link) Attach(P1->coef, P1->expon, &rear);
for(;P2;P2 = P2->link) Attach(P2->coef, P2->expon, &rear);
//收尾工作
rear->link = NULL;
temp = front;
front = front->link;
free(temp);
return front;
}
/**
* 将多项式的指数和系数保存到一个新的结点,然后连接到队列尾部
* */
void Attach(int c, int e, Polynomial *pRear)
{
//创建结点P,用于存放多项式的数据
Polynomial P = (Polynomial) malloc(sizeof(struct PolyNode));
//结点数据赋值
P->coef = c;
P->expon = e;
P->link = NULL;
//把P插入到队尾,P成为了新的队尾,后面要更新pRear
(*pRear)->link = P;
//让pRear再次指向队尾结点
*pRear = P;
}
/**
* a 大于 b 返回 1
* a 小于 b 返回 -1
* a 等于 b 返回 0
* */
int Compare(int a, int b)
{
if(a>b)
return 1;
else if(a<b)
return -1;
else
return 0;
}
C语言数据结构应用之多项式相加
最新推荐文章于 2023-04-28 16:43:16 发布