数据结构多项式相加
作者:互联网
多项式相加数据域有两个int
一个放x的一个放x前面的值
代码如下:
#include <stdio.h>
#include <stdlib.h>//包含malloc(),free()函数
typedef struct LNode{
float coef;//系数
int expn;//指数
LNode *next;
}LNode, *LinkList;//指针
void CreatPolyn(LinkList &L ,int m){
LinkList p,q;
L = (LinkList)malloc(sizeof(LNode));//头结点
L->next = NULL;
p = L;
for (int i = 0; i < m; i++)
{
printf("enter coef and expn:");
q = (LinkList)malloc(sizeof(LNode));//生成新结点
q ->next = NULL;
scanf("%f %d",&q->coef,&q->expn);
p->next = q;//接到链尾
p = q;//更新p
}
}
LinkList AddPolyn(LinkList &La, LinkList &Lb){
LinkList qa, qb, qc, Lc, qf1, qf2;//qf1, qf2用于释放结点的临时存储结点
qa = La->next;//qa,qb指向对应链表当前结点
qb = Lb->next;
qc = Lc = La;//Lc是结果要存入的链表的头结点,qc表示当前指向结点
while(qa && qb){
if (qa->expn == qb->expn)
{
qa->coef += qb->coef;//遇到指数相同,系数相加到qa
if (qa->coef != 0)//系数相加不为结果为0时
{
qc->next =qa;//链入qa
qc = qa;//当前结点后移
//这时要释放qb当前结点
qf1 = qb;
qa = qa->next;
qb = qb->next;
free(qf1);
}else{//系数相加为结果为0时,指针后移,释放结点
qf1 = qb;
qf2 = qa;
qa = qa->next;
qb = qb->next;
free(qf1);
free(qf2);
}
}else if (qa->expn > qb->expn)//剩下指数不相等情况哪个指数小先存哪个
{
qc->next = qb;
qc = qb;
qb = qb->next;
}else
{
qc->next = qa;
qc = qa;
qa = qa->next;
}
}
qc->next =qa?qa:qb;//若有一条链剩余,就把剩下的都链入
free(Lb);//释放Lb头结点
return(Lc);
}
void PrintfPolyn(LinkList &L){
while (L->next)//非空时
{
L = L->next;
printf("your result is %.2f %d \n",L->coef,L->expn);
}
}
int main() {
int n1;
int n2;
LinkList La, Lb, Lc;
printf("enter first num:");
scanf("%d", &n1);
CreatPolyn(La,n1);
printf("enter second num:");
scanf("%d", &n2);
CreatPolyn(Lb,n2);
Lc = AddPolyn(La, Lb);
PrintfPolyn(Lc);
system("pause");
return 0;
}
标签:LinkList,结点,多项式,相加,next,qa,qc,qb,数据结构 来源: https://blog.csdn.net/S_JYYDS/article/details/123604971