/* 处理多项式 */
#include "stdio.h"
struct plist
{
int coef;
int exp;
struct plist *next;
};
typedef struct plist pnode;
typedef pnode *plink;
/*多项式含头结点的循环链表的输出*/
void printpoly(plink poly)
{
plink ptr;
ptr=poly->next;
while(poly!=ptr)
{
/*输出结点数量*/
printf("%d^%d",ptr->coef,ptr->exp);
ptr=ptr->next;
if(poly!=ptr)
printf("+");
}
printf("/n");
}
/*使用数组创建多项式*/
plink createpoly(int *array,int len)
{
plink head;
plink before;
plink new_node;
int i;
/*创建头结点*/
head=(plink)malloc(sizeof(pnode));
if(!head) return NULL;
head->exp=-1;
before=head;
for(i=len-1;i>=0;i--)
if(array[i]!=0)
{
/*分配结点内存*/
new_node=(plink)malloc(sizeof(pnode));
if(!new_node) return NULL;
new_node->coef=array[i];
new_node->exp=i;
new_node->next=NULL;
before->next=new_node;
before=new_node;
}
new_node->next=head;
return head;
}
/*多项式相加*/
plink polyadd(plink poly1,plink poly2)
{
plink head1,head2,result,before,new_node;
head1=poly1->next;
head2=poly2->next;
/*创建头结点而分配结点内存*/
result=(plink)malloc(sizeof(pnode));
if(!result) return NULL;
result->exp=-1;
before=result;
while(poly1!=head1||poly2!=head2)
{
/*分配内存结点*/
new_node=(plink)malloc(sizeof(pnode));
if(!new_node) return NULL;
if(head1->exp<head2->exp)/*多项式2的指数大*/
{
new_node->coef=head2->coef;/*设置系数*/
new_node->exp=head2->exp;/*设置指数*/
head2=head2->next;/*指向下一个结点*/
}
else
if(head1->exp>head2->exp)/*多项式1的指数大*/
{
new_node->coef=head1->coef;/*设置系数*/
new_node->exp=head1->exp;/*设置指数*/
head1=head1->next;/*指向下一个结点*/
}
else
{
/*系数相加*/
new_node->coef=head1->coef+head2->coef;
new_node->exp=head1->exp;/*设置指数*/
head1=head1->next;/*指向下一个结点*/
head2=head2->next;/*指向下一个结点*/
}
before->next=new_node;/*将前结点指向新结点*/
before=new_node;/*新结点成为前结点*/
}
new_node->next=result;/*创建环状链表*/
return result;
}
/*主程序*/
void main()
{
plink poly1,poly2,result;
int list1[6]={4,0,3,0,7,0};
int list2[6]={9,7,1,0,5,6};
poly1=createpoly(list1,6);
printf("多项式1内容:");
printpoly(poly1);
poly2=createpoly(list2,6);
printf("多项式2内容:");
printpoly(poly2);
result=polyadd(poly1,poly2);
printf("多项式相加结果");
printpoly(result);
}
处理多项式
最新推荐文章于 2022-03-13 16:37:04 发布