#include<iostream>
using namespace std;
typedef struct node {
int ele;
int po;
struct node *next;
} Node,*List;
void Create(List &L,int n) {
List p,flag;
L=(List)malloc(sizeof(Node));
L->next=NULL;
flag=L;
printf("输入%d数据\n",n);
for(int i=1; i<=n; i++) {
p=(List)malloc(sizeof(Node));
scanf("%d%d",&p->ele,&p->po);
flag->next=p;
flag=flag->next;
}
p->next=NULL;
}
void Print(List L) {
List p=L->next;
while(p) {
if(p->ele != 0) {
printf("%dX^%d",p->ele,p->po);
}
if(p->next) {
printf("+");
}
p=p->next;
}
printf("\n");
}
List Sum(List La,List Lb) {
List pa, pb, pc, Lc;
pa = La->next;
pb = Lb->next;
Lc = pc = La;
while(pa&&pb) {
if(pa->po < pb->po) {
pc->next = pa;
pc = pa;
pa = pa->next;
} else if (pa ->po > pb->po) {
pc->next = pb;
pc = pb;
pb = pb->next;
} else {
pa->ele = pa->ele + pb->ele;
pc->next = pa;
pc = pa;
pa = pa->next;
pb = pb->next;
}
}
pc->next = pa ? pa:pb;
return Lc;
}
int main() {
List ha,hb,hc; //定义三个多项式
printf("ha的项数");
printf("非递减输入项式ha ");
int n;
scanf("%d",&n);
Create(ha,n);
printf("hb的项数");
printf("非递减输入项式hb ");
scanf("%d",&n);
Create(hb,n);
printf("项式ha :");
Print(ha);
printf("项式hb :");
Print(hb);
hc = Sum(ha,hb);
printf("项式hc :");
Print(hc);
return 0;
}
多项式ADT
最新推荐文章于 2024-04-19 15:40:31 发布