# 一元多项式的相加

    struct PolyNode
{
int coef;
int expon;
};
typedef struct PolyNode* Polynomial;
Polynomial P1, P2,PS;
int Compare(int e1, int e2)
{
if (e1 > e2)
return 1;
else if (e2 < e2)
return -1;
else if (e2 == e1)
return 0;
}
void Attach(int c, int e, Polynomial *PRear)
{
Polynomial P;
P = (Polynomial)malloc(sizeof(struct PolyNode));
P->coef = c;
P->expon = e;
(*PRear) = P;
}
{
Polynomial P,Rear,t;
int c, e, N;
printf("请输入有多少项：\n");
scanf("%d", &N);
P = (Polynomial)malloc(sizeof(struct PolyNode));
Rear = P;
printf("请输入每一项的系数，和指数用空格隔开：\n");
while (N--)
{
scanf("%d %d", &c, &e);
Attach(c, e, &Rear);
}
t = P; P = P->link; free(t);
return P;
}

Polynomial Add(Polynomial P1, Polynomial P2)
{
Polynomial front, rear, temp;
int sum;
rear = (Polynomial)malloc(sizeof(struct PolyNode));
front = rear;
while (P1&&P2)
{
switch (Compare(P1->expon, P2->expon))
{
case1:
{
Attach(P1->coef, P1->expon, &rear);
break;
}
case -1:
{
Attach(P2->coef, P2->expon, &rear);
break;
}
case 0:
{
sum = P1->coef + P2->coef;
if (sum)Attach(sum, P1->expon, &rear);
break;
}
}
}
Attach(P1->coef,P1->expon,&rear);

Attach(P2->coef,P2->expon,&rear);
temp = front;
free(temp);
return front;
}
void PrintPoly(Polynomial P)
{
int flag = 0;
if (!P){ printf("0\n"); return; };
while (P)
{
if (flag == 0)
flag = 1;
else
printf(" ");
printf("%d %d", P->coef, P->expon);
}
}
int main()
{
PS = Add(P1, P2);
PrintPoly(PS);
return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120