这里是写了很多遍才过的,注意审题,要不然会有得分点过,第一个,零次多项式,就是系数全部为零的多项式,还有整形范围内,coef系数这个地方要处理成int ,严蔚敏著的《数据结构》上面用的float,但在这会显示一个点不过。
#include <stdio.h>
#include <iostream>
using namespace std;
typedef struct PNode
{
int coef;
int expn;
struct PNode* next;
}PNode, * Polynomial;
void CreatePolyn(Polynomial& P, int n)
{
PNode* r; /*链表的创立*/
P = new PNode;
P->next = NULL;
r = P;
for (int i = 0; i < n; i++)
{
PNode *s; /*需要多少个节点,创立多少个*/
s = new PNode;
s->next = NULL;
scanf("%d %d", &s->coef, &s->expn);
r->next = s;
r = r->next;
}
}
void Print(Polynomial p)
{
if (p->next == NULL)
{
printf("0 0");/*这里就是判断是否为零多项式,因为,如果全部的
系数抵消了,下面的P3其实没有指向任何节点,
也就是头节点后面最终是个NULL,这种情况就是零多项式了*/
return;
}
p = p->next;
while (p)
{
if(p->next!=NULL)
printf("%d %d ", p->coef, p->expn);
else
printf("%d %d", p->coef, p->expn);
p = p->next;
}
}
void AddPolyn(Polynomial& Pa, Polynomial& Pb)
{
PNode* p1, * p2,*p3,*r;
p1 = Pa->next; /*这里用P1,P2作为两个链表的首元节点,
p3的作用是,指向Pa,然后代替Pa在后面链接节点
其实这里就是默认了用Pa当作最终合并链表的头节点
这里我是让第一个链表当作最终节点的头节点*/
p2 = Pb->next;
p3 = Pa;
int sum = 0;
while (p1 && p2)
{
if (p1->expn == p2->expn)
{
sum = p1->coef + p2->coef;
if (sum != 0)
{
p1->coef = sum;
p3->next = p1;
p3 = p1;
p1 = p1->next;
r = p2;
p2 = p2->next;
delete r;
}
else
{
r = p1;
p1 = p1->next;
delete r;
r = p2;
p2 = p2->next;
delete r;
}
}
else if (p1->expn > p2->expn)
{
p3->next = p1;
p3 = p1;
p1 = p1->next;
}
else
{
p3->next = p2;
p3 = p2;
p2 = p2->next;
}
}
p3->next = p1 ? p1 : p2; /*这里是把剩下的节点链接上去*/
delete Pb;
}
int main()
{
PNode *P,*P1;
int n,n1;
cin >> n ;
CreatePolyn(P, n);
cin >> n1;
CreatePolyn(P1, n1);
AddPolyn(P, P1);
Print(P);
return 0;
}