您的位置:首页 > 其它

一元多项式相加

2013-11-11 18:16 316 查看
#include<stdio.h>

#include<stdlib.h>

typedef struct s

{
int coef;
int index;
struct s *next;

}ss;

ss*creat()                                            //创建带头结点的链表

{
ss*head,*p,*s;
int m;
if((head=(ss*)malloc(sizeof(ss)))==NULL)
{
printf("不能分配空间\n");
exit(0);
}
p=head;
scanf("%d",&m);
while(m!=0)
{

        if((s=(ss*)malloc(sizeof(ss)))==NULL)
{
printf("不能分配空间\n");
exit(0);
}
s->coef=m;
scanf("%d",&m);
s->index=m;
p->next=s;
p=s;

        scanf("%d",&m);
}
p->next=NULL;
return head;

}

void plus(ss*head1,ss*head2)                        //相加函数

{
ss*p,*q,*s;
for(p=head1->next;p!=NULL;p=p->next)
for(s=head2,q=head2->next;q!=NULL;)
{
if(p->index==q->index)
{
p->coef=p->coef+q->coef;
s->next=q->next;
free(q);
q=s->next;
}
else 
{
s=q;
   q=q->next;
}
}
for(p=head1;p->next;p=p->next);
p->next=head2->next;

}

void sort(ss*head1)                               //升幂排序(冒泡

{
ss*p,*q,*temp;
temp=head1;
for(p=head1->next;p!=NULL;p=p->next)
for(q=p->next;q!=NULL;q=q->next)
if(p->index>q->index)
{
temp->index=p->index;p->index=q->index;q->index=temp->index;

                temp->coef=p->coef;p->coef=q->coef;q->coef=temp->coef;
}

})

void print(ss*head)                          //显示函数

{
ss*p;
int i=1;
p=head->next;
while(p!=NULL)
if(p->coef!=0)
{
if(p->index==0)
{
if(i==1)
printf("%d",p->coef);
else if(p->coef>0)
printf("+%d",p->coef);

else
printf("%d",p->coef);
i++;
}
else if(p->index==1)
{
if(i==1)
printf("%d",p->coef);
else if(p->coef>1)
printf("+%d",p->coef);
else if(p->coef==1)
printf("+");
else if(p->coef==-1)
printf("-");

else
printf("%d",p->coef);

printf("x");
i++;
}
else if(i==1)
{
if(p->coef==1)
printf("x^");
else if(p->coef==-1)
printf("-x^");
else
printf("%dx^",p->coef);

                printf("%d",p->index);
i++;
}
else if(p->coef>1)
printf("+%dx^%d",p->coef,p->index);
else if(p->coef==1)

                printf("+x^%d",p->index);
else if(p->coef==-1)

                printf("-x^%d",p->index);
else
printf("%dx^%d",p->coef,p->index);
p=p->next;
}
else
p=p->next;

}

main()

{
ss*head1,*head2;
printf("\t\t    ***欢迎使用两个多项式相加的程序***\n");
printf("请输入第一个多项式:\n\t  格式如下:-2 5 3 4 -8 6 0代表-2x^5+3x^4-8x^6其中“0”是结束符\n");
head1=creat();

    printf("请输入第二个多项式:\n");
head2=creat();
printf("两多项式相加结果:\n");
printf("(");
print(head1);

    printf(")+(");

    print(head2);

    printf(")=");
plus(head1,head2);
sort(head1);
print(head1);

    putchar(10);

}   //so easy!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息