<pre name="code" class="cpp">#include"stdio.h"
struct poly{
int exp;
int coef;
struct poly *next;
};
//创建多项式
struct poly *createPolyLink(int p[][2],int num)
{
struct poly *head;
struct poly *newNode;
struct poly *temp;
int i;
head=(struct poly *)malloc(sizeof(struct poly));
if(num<=0)
return NULL;
head->next =NULL;
for(i=0;i<num;i++)
{
newNode=(struct poly *)malloc(sizeof(struct poly));
newNode->coef =p[i][1];
newNode->exp =p[i][0];
newNode->next =NULL;
if(head->next ==NULL)
{
head->next =newNode;
temp=newNode;
}
else
{
temp->next =newNode;
temp=newNode;
}
}
return head;
}
//输出多项式
void printPoly(struct poly *p)
{
struct poly *temp;
if(p->next ==NULL)
return ;
temp=p->next ;
while(temp)
{
printf("coef: %d,exp: %d\n",temp->coef ,temp->exp );
temp=temp->next ;
}
}
//对链表进行排序
struct poly *polySort(struct poly *p)
{
struct poly *startNode,*endNode,*pra,*temp1,*temp2;
int temp;
int tem;
startNode=p->next ;
endNode=pra=startNode;
if(startNode->next ==NULL)
return p;
//找到链表的表尾
while(endNode->next )
{
pra=endNode;
endNode=endNode->next ;
}
while(pra!=startNode)
{
temp1=startNode;
temp2=startNode->next ;
while(1)
{
if(temp1->exp>temp2->exp )
{
temp=temp1->exp ;
tem=temp1->coef ;
temp1->exp =temp2->exp ;
temp1->coef =temp2->coef ;
temp2->exp =temp;
temp2->coef =tem;
}
if(temp2==endNode)
break;
temp1=temp2;
temp2=temp2->next ;
}
endNode=startNode;
while(endNode->next!=pra )
endNode=endNode->next ;
pra=endNode;
endNode=endNode->next ;
}
return p;
}
//合并两个链表
struct poly *conLink(struct poly *a,struct poly *b)
{
struct poly *link1,*link2,*temp1,*temp2;
struct poly *temp,*pra;
link1=a->next ;
link2=b->next ;
temp2=link2->next ;
while(link1->next !=NULL&&link2!=NULL)
{
temp1=link1->next ;
if(temp1->exp>link2->exp )
{
link2->next=link1->next ;
link1->next =link2;
link2=temp2;
temp2=temp2->next ;
link1=link1->next ;
}else if(temp1->exp==link2->exp )
{
temp1->coef=temp1->coef +link2->coef ;
if(temp1->coef ==0)
{
link1->next =temp1->next;
link2=temp2;
if(link2 == NULL)
break;
temp2=temp2->next ;
continue;
}
link1=temp1;
link2=temp2 ;
if(link2 == NULL)
break;
temp2=temp2->next ;
}else
{
link1=temp1;
}
}
if(link2!=NULL)
{
while(link2)
{
link1->next =link2;
link1=link2;
link2=link2->next ;
}
}
return a;
}
struct poly *comLink(struct poly *a,struct poly *b)
{
struct poly *link1,*link2;
link1=a->next ;
link2=b->next ;
if(link1->exp <link2->exp)
return conLink(a,b);
else
return conLink(b,a);
}
void main()
{
struct poly *A;
struct poly *B;
struct poly *addPoly;
int a[3][2]={
{5,2},
{2,3},
{3,4}
};
int b[3][2]={
{3,-4},
{4,3},
{5,4}
};
printf("多项式求和:\n");
A=createPolyLink(a,3);
//输出创建的多项式链表
printf("输出创建的多项式链表\n");
printPoly(A);
B=createPolyLink(b,3);
//输出创建的多项式链表
printf("输出创建的多项式链表\n");
printPoly(B);
//对链表进行排序
A=polySort(A);
printf("排序后的链表A\n");
printPoly(A);
B=polySort(B);
printf("排序后的链表B\n");
printPoly(B);
//合并多项式
printf("合并后的链表\n");
addPoly=comLink(A,B);
printPoly(addPoly);
getchar();
}
多项式求和(用链表)
最新推荐文章于 2022-04-14 16:46:34 发布