希望哪位大神可以帮我解释一下算法的每一句,谢谢了
#include<stdio.h> #include<stdlib.h>
typedef struct polynomial
{
float cofe; //系数
int expn; //指数
struct polynomial *next;
}*polyn,polynomial;
//创建多项式
void Insert(polyn p,polyn h) //头结点是h,新结点p
{ //顺序插入结点
if (p->cofe==0)
free(p); //若系数为0释放结点
else
{
polyn q1,q2;
q1=h;
q2=h->next;
while (q2&&p->expn<q2->expn)
{ //查找插入位置
q1=q2;
q2=q2->next;
}
if(q2&&p->expn==q2->expn)
{
//将指数相同相合并
q2->cofe+=p->cofe;
free(p);
if(!q2->cofe)
{ //若系数为0释放结点
q1->next=q2->next;
free(q2);
}
}
else
{ //指数为新时将结点插入
p->next=q2;
q1->next=p;
}
} }
polyn Createpolyn(polyn head,int m)
{//建立一个头指针为head一元多项式
int i;
polyn p;
p=head=(polyn)malloc(sizeof(polynomial));
head->next=NULL;
for(i=0;i<m;i++)
{ p=(polyn)malloc(sizeof(polynomial));
printf(" 输入第%d项的系数与指数:",i+1);
scanf("%f%d",&p->cofe,&p->expn);
Insert(p,head); } //调用Insert函数插入结点
return head;
}
void Printfpolyn(polyn p) //打印多项式
{
polyn q=p->next;
int flag=1;
if(!q)
{
putchar('0');
printf("\n");
return;
}
while(q)
{
if(q->cofe>0&&flag!=1)
putchar('+');
if(q->cofe!=1&&q->cofe!=-1)
{
printf("%g",q->cofe);
if(q->expn==1)
putchar('x');
else
printf("x^%d",q->expn);
}
else
{
if(q->cofe==1)
{
if(!q->expn)
putchar('1');
else if(q->expn==1)
putchar('x');
else printf("x^%d",q->expn );
}
if(q->expn==-1)
{
if(!q->expn)
printf("-1");
else if(q->expn==1)
printf("-x");
else
printf("-x^%d",q->expn);
} }
q=q->next;
flag++; }
}
int Compare(polyn a,polyn b)
{
if(a&&b)
{if(!b||a->expn>b->expn) return 1;
else if(!a||a->expn<b->expn) return -1;
else return 0;
}
else if(!a&&b) return -1;
else return 1;
}
polyn Addpolyn(polyn pa,polyn pb)
{
polyn qa=pa->next;
polyn qb=pb->next;
polyn headc,hc,qc;
headc=hc=(polyn)malloc(sizeof(polynomial));
hc->next=NULL;
while(qa||qb) //qa或qb为空
{
qc=(polyn)malloc(sizeof(polynomial));
switch(Compare(qa,qb))
{
case 1: //pb中当前结点的的指数值小
{
qc->cofe=qa->cofe;
qc->expn=qa->expn;
qa=qa->next;
break;
}
case 0: //指数值相等
{
qc->cofe=qa->cofe+qb->cofe;
qc->expn=qa->expn;
qa=qa->next;
qb=qb->next;
break;
}case -1: //多项式pa中当前结点的指数值小
{ qc->cofe=qb->cofe;
qc->expn=qb->expn;
qb=qb->next;
break; }
} if(qc->cofe!=0)
{ qc->next=hc->next;
hc->next=qc;
hc=qc; }
else free(qc);
}
return headc;
}
polyn Subpolyn(polyn pa,polyn pb)
{ polyn h=pb;
polyn p=pb->next;
polyn pd;
while(p)
{ p->cofe*=-1; p=p->next; }
pd=Addpolyn(pa,h);
for(p=h->next;p;p=p->next) {
p->cofe*=-1; }
return pd; }
int main() {
int m,n,a; char flag;
polyn pa=0,pb=0,pc;
printf("输入a的项数:");
scanf("%d",&m); pa=Createpolyn(pa,m);
printf("输入b的项数:");
scanf("%d",&n);
pb=Createpolyn(pb,n);
printf(" A:输出a-b:");
while(a) { printf("选择操作:\n");
getchar();
scanf("%c",&flag);
switch(flag) {
case 'A':
case 'a':
{
pc=Subpolyn(pa,pb);
printf("a-b=");
Printfpolyn(pc);
break;
}
default:
printf("选择错误!"); }
}
return 0;
}