#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct node
{
int coef;
int exp;
struct node *next;
}PNode;
PNode *Creat_Linkst(int n);
void PolyAdd(PNode *pa,PNode *pb);
void Print_Linkst(PNode *H);
int main()
{
// System("color e");
PNode *HA,*HB;
int la,lb;
printf("enter la,lb:");
scanf("%d,%d",&la,&lb);
printf("\ncreat HA\n");
HA=Creat_Linkst(la);
printf("A(x)=");
Print_Linkst(HA);
printf("\ncreat HB\n");
HB=Creat_Linkst(lb);
printf("B(x)=");
Print_Linkst(HB);
PolyAdd(HA,HB);
printf("\nA(x)+B(x)=");
Print_Linkst(HA);
return 0;
}
PNode *Creat_Linkst(int n)
{
PNode *head,*p,*s;
int i;
// head=new PNode;
head->next=NULL;
p=head;
printf("enter coef,exp:\n");
for(i=1;i<=n;++i)
{
s=new PNode;
scanf("%d,%d",&s->coef,&s->exp);
s->next=NULL;
p->next=s;
p=s;
}
return(head);
}
void PolyAdd(PNode *pa,PNode *pb)
{
PNode *pre,*qa,*qb,*q;
int sum;
pre=pa;
qa=pa->next;
qb=pb->next;
while(qa && qb)
{
if(qa->exp==qb->exp)
{
sum=qa->coef+qb->coef;
if(sum){ qa->coef =sum;pre=qa;}
else { pre->next=qa->next;delete(qa);}
qa=pre->next;
q=qb;qb=qb->next;delete(q);
}
else
{
if (qa->exp>qb->exp)
{
pre=qa;qa=qa->next;
}
else
{
pre->next=qb;pre=qb;
qb=qb->next;pre->next=qa;
}
}
}
if (qb)pre->next=qb;
delete(pb);
}
void Print_Linkst(PNode *H)
{
PNode *p;
p=H->next;
while(p->next)
{
printf("%dx^%d+",p->coef,p->exp);
p=p->next;
}
if(p->exp)
printf("%dx^%d\n",p->coef,p->exp);
else printf("%d\n",p->coef);
}
数据结构源码笔记(C语言描述)汇总: