数据结构C语言编程—单链表实现多项式相加

#include<stdio.h>
#include<malloc.h>
#include<string.h>
#include<windows.h>
typedef struct node
{
int coef,exp;
struct node *next;
}JD,*LinkList;

void add_poly(JDpa,JDpb) /多项式相加函数 ,通过判断指数大小来推动程序进行/
{
JD *p,*q,*u,*pre;
int x;
p=pa->next;
q=pb->next;
pre=pa;
while((p!=NULL)&&(q!=NULL))
{
if(p->expexp)
{
pre=p;
p=p->next;
}
else if(p->exp==q->exp)
{
x=p->coef+q->coef;
if(x!=0)
{
p->coef=x;
pre=p;
}
else
{
pre->next=p->next;
free§;
}
p=pre->next;
u=q;
q=q->next;
free(u);
}
else
{
u=q->next;
q->next=p;
pre->next=q;
pre=q;
q=u;
}
}
if(q!=NULL)
pre->next=q;
free(pb);
}

void PrintList(LinkList head)
{
JD *p;
printf("\t\t\t");
for(p=head->next;p->next!=NULL;p=p->next)
printf("%dx^%d + “,p->coef,p->exp);
printf(”%dx^%d",p->coef,p->exp);
printf("\n");
}

LinkList CreateList(void) /多项式创建函数/
{
int coef,exp;
JD *head=(JD *)malloc(sizeof(JD));
JD *s,*r;
r=head;
printf("\t\tplease input the coef and exp:\n");
while(1)
{
printf("\t\tthe coef:");
scanf("%d",&coef);
if(coef0)break;
printf("\n\t\tthe exp:");
scanf("%d",&exp);
printf("\t\t
==========================\n");
s=(JD *)malloc(sizeof(JD));
s->coef=coef;
s->exp=exp;
r->next=s;
r=s;
}
r->next=NULL;
return head;
getchar();
}

void main()
{
LinkList pa,pb;
pa=CreateList(); /生成pa指向的多项式/
system(“cls”);
pb=CreateList(); /生成pb指向的多项式/
system(“cls”);
printf("\n\n\n\t\t=The Addition Of One-Letter-Polynomial=\n");
printf("\n\t\tThe first one-letter- polynomial:\n");
PrintList(pa);
printf("\n\t\t
The second one-letter- polynomial:\n");
PrintList(pb);
printf("\n\t\t========The final one-letter- polynomial:\n");
add_poly(pa,pb);
PrintList(pa);
getchar();
getch();
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长风弦歌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值