📄 mypoly.c
字号:
#include<stdio.h>
#include<malloc.h>
struct dxs
{
int zhs;
float xis;
struct dxs *next;
}*L1,*L2;
void main()
{
struct dxs * initList(struct dxs *L);
struct dxs *inputPoly(struct dxs *L);
struct dxs *insertElemt(struct dxs *L,int zhs,float xis);
void showList(struct dxs *L);
void welcome(void);
struct dxs* mergList(struct dxs *L1,struct dxs *L2);
welcome();
printf("================Please input the first Poly================\n");
L1=initList(L1);/*初始化表*/
L1=inputPoly(L1);/*插入新的多项式*/
showList(L1);/*显示多项式*/
printf("=============Please input the second Poly================\n");
L2=initList(L2);/*初始化表*/
L2=inputPoly(L2);/*插入新的多项式*/
showList(L2);/*显示多项式*/
/*合并两个多项式*/
printf("===============Printf the result=================\n");
showList(mergList(L1,L2));
}
void welcome()
{
printf("\t***********************************************\n");
printf("\t*\tPlease input XiShu ZhiShu\t *\n");
printf("\t*\tAs this format xishu,zhishu\t *\n");
printf("\t*\tEnd inputing with \"Q\"\t\t *\n");
printf("\t*\t==Designed by Zhao Chao== \t *\n");
printf("\t***********************************************\n");
}
struct dxs * initList(struct dxs *L)
{
/*创建带头结点的链表*/
L=(struct dxs *)malloc(sizeof(struct dxs));
L->next=NULL;
return L;
}
/*插入新的多项式信息*/
struct dxs *inputPoly(struct dxs *L)
{
char end;
int zhs;
float xis;
struct dxs *newL=L;
while(end!='Q')
{
scanf("%f,%d",&xis,&zhs);
newL=insertElemt(newL,zhs,xis);
end=getchar();
}
return newL;
}
/*向链表中插入新的元素*/
struct dxs *insertElemt(struct dxs *L,int zhs,float xis)
{
struct dxs *newdxs=(struct dxs *)malloc(sizeof(struct dxs));
newdxs->zhs=zhs;
newdxs->xis=xis;
newdxs->next=L->next;
L->next=newdxs;
return L;
}
/*显示多项式*/
void showList(struct dxs *L)
{
struct dxs *p=L->next;
char y[]={"f(x)="};
int nodenum=1;
printf("%s",y);
while(p)
{
switch(nodenum)
{
case 1:
printf("%.2fX%d",p->xis,p->zhs);
break;
default:
printf("+%.2fX%d\n",p->xis,p->zhs);
break;
}
p=p->next;
nodenum++;
}
getch();
}
/*
合并两个多项式
通过对L2中的每个元素与L1所有的元素扫描,找出指数相等的,
不等的对L1进行插入删除操作
*/
struct dxs* mergList(struct dxs *L1,struct dxs *L2)
{
struct dxs* pa,*pb,*priora,*insertnode;
pa=L1->next;pb=L2->next;
priora=L1;/*记录抵消的节点前一个节点*/
while(pb)
{
/*除非找见指数相等的进行处理,然后跳出,否则一次扫描后pa=NULL*/
while(pa)
{
if(pb->zhs==pa->zhs)/*指数相等的项*/
{
if(pb->xis+pa->xis==0)/*系数绝对值相等符号相反*/
{
/*抵消项*/
priora->next=pa->next;
break;
}
else
{
pa->xis=pa->xis+pb->xis; /*系数不等系数相加*/
break;
}
}
priora=pa;/*用于记录合并不同项时记录当前节点的前驱*/
pa=pa->next;
}
/*查找了整个L1表没有找到与当前pb指数相等的项*/
if(pa==NULL)
{
/*新创建一个与当前pb内容相同的元素,并将其连接到L1的末尾*/
insertnode=(struct dxs *)malloc(sizeof(struct dxs));
insertnode->zhs=pb->zhs;
insertnode->xis=pb->xis;
insertnode->next=pa;
priora->next=insertnode;
}
/*将pa及其前驱重初始化,以便下一个pb元素扫描整个L1表*/
priora=L1;
pa=L1->next;
pb=pb->next;
}
free(pb);
return L1;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -