// test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include
#include
typedef struct polynode
{
int coef;
//系数
int exp;
//指数
struct polynode *next;
}polynode;
polynode *CreateListR()
{
polynode *s,*r,*h;
int c,e;
h=(polynode *)malloc(sizeof(polynode));
r=h;
printf("enter coef :");
scanf("%d",&c);
printf("enter exp :");
scanf("%d",&e);
while(c!=0)
{
s=(polynode *)malloc(sizeof(polynode));
s->coef=c;
s->exp=e;
r->next=s;
r=s;
printf("enter coef :");
scanf("%d",&c);
printf("enter exp :");
scanf("%d",&e);
}
r->next=NULL;
return (h);
}
void Dispolynode(polynode *p)
//输出函数,打印出一元多项式
{
printf("\n");
while(p->next!=NULL)
{
p=p->next;
printf(" %d*x^%d",p->coef,p->exp);
}
}
void sumpolynode(polynode *ha, polynode *hb)
{
polynode *p,*q,*pre,*temp;
int sum;
p=ha->next;
q=hb->next;
pre=ha;
while(p!=NULL&&q!=NULL)
{
if(p->exp
{
pre->next=p;
pre=pre->next;
p=p->next;
}
else if(p->exp==q->exp)
{
sum=p->coef+q->coef;
if(sum!=0)
{
p->coef=sum;
pre->next=p;
pre=pre->next;
p=p->next;
temp=q;
q=q->next;
free(temp);
}
else //如果系数和为零,则删除结点p与q,并将指针指向下一个结点
{
temp=p->next;
free(p);
p=temp;
temp=q->next;
free(q);
q=temp;
}
}
else
{
pre->next=q;
pre=pre->next;
q=q->next;
}
}
if(p!=NULL) //将多项式A中剩余的结点加入到和多项式中
pre->next=p;
else
pre->next=q;
}
void multipoly(polynode *ha,polynode *hb)
{
polynode *q,*p,*n,*m;
p=ha->next;
n = (polynode *)malloc(sizeof(polynode));
n->next = NULL;
m = (polynode *)malloc(sizeof(polynode));
while(p!=NULL)
{
m->next = NULL;
for(q=hb->next;q;q=q->next)
{
polynode *newNode = (polynode *)malloc(sizeof(polynode));
newNode->coef=(p->coef*q->coef);
newNode->exp=(p->exp+q->exp);
newNode->next=m->next;
m->next = newNode;
}
sumpolynode(n, m);
p=p->next;
}
printf("The product of this two polynomial:");
Dispolynode(n);
}
int main()
{
polynode *ha,*hb;
printf("Please enter the coef and exp of ha:\n");
ha=CreateListR();
Dispolynode(ha);
printf("\nPlease enter the coef and exp of hb:\n");
hb=CreateListR();
Dispolynode(hb);
//sumpolynode(ha, hb);
//Dispolynode(ha);
printf("\n");
multipoly(ha, hb);
getchar();
}