两个一元多项式相加需要考虑三种情况:指数相同、多项式一指数大于多项式二、多项式一小于多项式二,其中指数相同又可分成指数相加不为0和相加为0两种情况。
创建单链表用来存储一元多项式,主要思想是p2指数与p1指数作比较,p1>p2,删除p2连在p1前面;p1<p2,p1后移;p1=p2,删除p2更改p1的。(p1多项式一工作指针,p2多项式二工作指针)
结构体定义
typedef struct TagLnode{
int index;//指数域
int coef;//系数域
struct TagLnode *next;
}Lnode,*LinkList;
(1)指数相同
if (p1->index==p2->index){//指数相同
int e=p1->coef+p2->coef;//记录系数之和
temp=p2;//暂存p2的地址
L2->next=p2->next;//删除p2结点
p2=L2->next;//指针后移
delete temp;//释放temp
if (e==0){//系数为0
temp=p1;//暂存p1结点
p1front->next=p1->next;//删除p1结点
p1=p1front->next;//指针后移
delete temp;//释放temp
}
else{//系数不为0
p1->coef=e;
}
}
(2)多项式一的指数大于多项式二的指数
else if (p1->index>p2->index){//p1指数大于p2指数
L2->next=p2->next;//删除p2结点
p2->next=p1;//p2接在p1前面
p1front->next=p2;//p1前驱接上p2
p1front=p2;//指针后移
p2=L2->next;//p2指向新的L2地址
}
(3)多项式一的指数小于多项式二的指数
else if (p1->index<p2->index){//p1指数小于p2指数
//L1链表指针后移
p1=p1->next;
p1front=p1front->next;
}
(4)多项式二仍有剩余,可以确定多项式二的剩余项均大于多项式一的项,直接连在多项式一后面。
if (p2!=NULL){//链2中仍有项,全连在链1的后面
p1front->next=p2;
L2->next=NULL;
}
源代码
#include <iostream>
using namespace std;
#include <stdlib.h>
typedef struct TagLnode{
int index;//指数域
int coef;//系数域
struct TagLnode *next;
}Lnode,*LinkList;
void InitList(LinkList &L){
L=new Lnode;
L->next=NULL;
}
void RearCreateList(LinkList &L,int n){
LinkList q,r;
r=L;
for (int i=1;i<=n;i++){
InitList(q);
cout<<"请输入第"<<i<<"个结点的系数和指数";
cin>>q->coef>>q->index;
r->next=q;
r=q;
}
}
void PrintList(LinkList &L){
LinkList p;
p=L->next;
while(p!=NULL){
cout<<p->coef<<"x^"<<p->index;
if (p->next!=NULL){
cout<<'+';
}
p=p->next;
}
}
void AdditionDoubleList(LinkList &L1,LinkList &L2){
LinkList p1,p2,p1front,temp;//p1是L1的工作指针,p2是L2的工作指针,p1front是p1的前驱,temp暂存需释放的结点
p1front=L1;
p1=L1->next;
p2=L2->next;
while (p1!=NULL&&p2!=NULL){//两条链都不为空
if (p1->index==p2->index){//指数相同
int e=p1->coef+p2->coef;//记录系数之和
temp=p2;//暂存p2的地址
L2->next=p2->next;//删除p2结点
p2=L2->next;//指针后移
delete temp;//释放temp
if (e==0){//系数为0
temp=p1;//暂存p1结点
p1front->next=p1->next;//删除p1结点
p1=p1front->next;//指针后移
delete temp;//释放temp
}
else{//系数不为0
p1->coef=e;
}
}
else if (p1->index>p2->index){//p1指数大于p2指数
L2->next=p2->next;//删除p2结点
p2->next=p1;//p2接在p1前面
p1front->next=p2;//p1前驱接上p2
p1front=p2;//指针后移
p2=L2->next;//p2指向新的L2地址
}
else if (p1->index<p2->index){//p1指数小于p2指数
//L1链表指针后移
p1=p1->next;
p1front=p1front->next;
}
}
if (p2!=NULL){//链2中仍有项,全连在链1的后面
p1front->next=p2;
L2->next=NULL;
}
}
void main(){
LinkList L1,L2;
int n1,n2;
InitList(L1);
InitList(L2);
cout<<"请输入L1的长度:";cin>>n1;
RearCreateList(L1,n1);
cout<<"请输入L2的长度:";cin>>n2;
RearCreateList(L2,n2);
cout<<"**********************************************";cout<<endl;
cout<<"初始L1:";
PrintList(L1);
cout<<endl;
cout<<"初始L2:";
PrintList(L2);
cout<<endl;
cout<<"**********************************************";cout<<endl;
AdditionDoubleList(L1,L2);
PrintList(L1);
system("pause");
}