1,多项式加法:与有序表的合并是一样的思路,从a链表头结点开始创建一个新的链表(指向头结点设置一个指针,这个指针是专门用作连结的,比如说单链表应用1里的删除A链表中与B重复的元素里、尾插法里的r、单链表应用2,3,都有设置这样的指针),然后设置两个指针,分别指向两个链表的首元结点。
然后就是依此比较指数.....
//实现两个多项式相加,并输出
typedef struct Pnode{
int coef;//系数
int expn;//指数
struct Pnode *next;
}Pnode,*polynomial;
#include<stdio.h>
void CreatePolyn(polynomial &p,int n);
void AddPolyn(polynomial &pa,polynomial &pb);
int main(){
int n1,n2;
polynomial pa,pb;
Pnode *p;
scanf("%d %d",&n1,&n2);
CreatePolyn(pa,n1);
CreatePolyn(pb,n2);
p=pa->next;
while(p){
printf("%d %d ",p->coef,p->expn);
p=p->next;
}
printf("\n");
p=pb->next;
while(p){
printf("%d %d ",p->coef,p->expn);
p=p->next;
}
printf("\n");
AddPolyn(pa,pb);
p=pa->next;
while(p){
printf("%d %d ",p->coef,p->expn);
p=p->next;
}
}
//建立一个多项式(建立一个有序的链表)
void CreatePolyn(polynomial &p,int n){
p=new Pnode;//如果要建立一个结点,那就new一块空间
p->next=NULL;
Pnode *s,*pre,*q;
for(int i=0;i<n;i++){
s=new Pnode;
scanf("%d %d",&s->coef,&s->expn);
pre=p;
q=p->next;
while(q&&q->expn<s->expn){
pre=q;
q=q->next;
}
s->next=q;
pre->next=s;
}
}
//开始创建 和多项式
void AddPolyn(polynomial &pa,polynomial &pb){
Pnode *p1,*p2,*p3,*r;//p1指向pa链表的首元结点,p2指向pb链表的首元结点,p3的作用是连结
p1=pa->next;
p2=pb->next;
p3=pa;
int sum;
while(p1&&p2){
if(p1->expn==p2->expn){
sum=p1->coef+p2->coef;
if(sum!=0){
p1->coef=sum;
p3->next=p1;
p3=p1;
p1=p1->next;
r=p2;
p2=p2->next;
delete r;
}else{
r=p1;p1=p1->next;delete r;
r=p2;p2=p2->next;delete r;
}
}else if(p1->expn<p2->expn){
p3->next=p1;
p3=p1;
p1=p1->next;
}else if(p1->expn>p2->expn){
p3->next=p2;
p3=p2;
p2=p2->next;
}
}
p3->next=p1?p1:p2;
delete pb;
}