多项式加法:
思路:
两个指针P1和P2分别指向这两个多项式第一个结点,不断循环: P1->expon==P2->expon: 系数相加,若结果不为0,则作为结果多项式对应项 系数。同时,P1和P2都分别指向下一项; P1->expon >P2->expon: 将P1的当前项存入结果多项式,并使P1指向下一项; P1->expon < P2->expon: 将P2的当前项存入结果多项式,并使P2指向下一项; 当某一多项式处理完时,将另一个多项式的所有结点依次复制到结果多项式中去。
代码如下
~~数据结构定义
~~
typedef struct LNode
* List
;
struct LNode
{
int c
;
int e
;
List Next
;
};
~~attach函数
~~
List
attach(int c
,int e
,List rear
)
{
List q
;
q
=(List
)malloc(sizeof(struct LNode
));
q
->c
=c
;
q
->e
=e
;
q
->Next
=NULL;
rear
->Next
=q
;
rear
=q
;
return rear
;
}
~~加法函数
~~
List
add(List p1
,List p2
)
{
~~空表头
~~
List p
,rear
,t;
p
=(List
)malloc(sizeof(struct LNode
));
p
->Next
=NULL;
rear
=p
;
while(p1
&&p2
) {
if(p1
->e
==p2
->e
){
if(p1
->c
+p2
->c
!=0)
rear
=attach(p1
->c
+p2
->c
,p1
->e
,rear
);
p1
=p1
->Next
;p2
=p2
->Next
;
}
else if(p1
->e
>p2
->e
){
rear
=attach(p1
->c
,p1
->e
,rear
);
p1
=p1
->Next
;}
else{
rear
=attach(p2
->c
,p2
->e
,rear
);
p2
=p2
->Next
;}
}
while(p1
){
rear
=attach(p1
->c
,p1
->e
,rear
);
p1
=p1
->Next
;
}
while(p2
){
rear
=attach(p2
->c
,p2
->e
,rear
);
p2
=p2
->Next
;
}
t
=p
;p
=p
->Next
;free(t
);
return p
;
}
乘法
思路
用P1的第一项×P2的每一项作为初始序列attach到结果序列运算P1的其余项与P2的每一项后将结果插入(Insert)到上述序列的合适位置插入函数包含情况有(指数相等项——注意系数和为0的删除(为0位置在尾部和中间处理方式不同)、指数不等项——有序插入新项)
代码
List
Find(List s
,int _e
)
{
List pre
=s
;
while(pre
->Next
){
if(pre
->Next
->e
<=_e
) return pre
;
pre
=pre
->Next
;
}
return pre
;
}
~~插入函数
~~
void Insert(int c
,int e
,List p
)
{
List item
,t
;
item
=(List
)malloc(sizeof(struct LNode
));
item
->c
=c
;item
->e
=e
;
if(p
->Next
==NULL)
{
if(item
->c
!=0)
{
p
->Next
=item
;
item
->Next
=NULL;
}
}
else if(p
->Next
->e
!=item
->e
){
item
->Next
=p
->Next
;
p
->Next
=item
;
}
else if(p
->Next
->e
==item
->e
){
if(item
->c
+p
->Next
->c
==0){
t
=p
->Next
;p
->Next
=t
->Next
;free(t
);}
else
p
->Next
->c
+=item
->c
;
}
}
List
Multi(List P1
,List P2
)
{
List s
;
List _P2
=P2
;
s
=(List
)malloc(sizeof(struct LNode
);
s
->Next
=NULL;
List rear
=s
;
if(P1
==NULL||P2
=NULL) return NULL;
while(P2
!=NULL){
rear
=attach((P1
->c
)*(P2
->c
),P1
->e
+P2
->e
,rear
);
P2
=P2
->Next
;
}
List tmp
=s
;s
=tmp
->Next
;free(tmp
);
P1
=P1
->Next
;P2
=_P2
;
while(P1
!=NULL){
while(P2
!=NULL){
int e
=P1
->e
+P2
->e
;
int c
=P1
->c
*P2
->c
;
List position
=Find(s
,e
);
Insert(c
,e
,position
);
P2
=P2
->Next
;
}
P1
=P1
->Next
;P2
=_P2
;
}
return s
;
}