#include<iostream>
#include<stdlib.h>
typedef struct _Node{
int a;
int exp;
struct _Node* next;
}Node;
typedef Node* linkList;
using namespace std;
void createlinkList(linkList &L){
L=(Node*)malloc(sizeof(Node));
L->next=NULL;
}
void init(linkList L,int n){
linkList P=L;
for(int i=0;i<n;i++){
linkList Q=(Node*)malloc(sizeof(Node));
cin>>Q->a;
cin>>Q->exp;
Q->next=P->next;
P->next=Q;
P=Q;
}
}
void insert(linkList L,int a,int exp){
linkList P=L;
while(P->next){
P=P->next;
}
linkList Q=(Node*)malloc(sizeof(Node));
Q->a=a;
Q->exp=exp;
Q->next=P->next;
P->next=Q;
}
linkList uni(linkList Q,linkList P,linkList L){
P=P->next;
Q=Q->next;
while(P&&Q){
if(P->exp==Q->exp){
insert(L,P->a+Q->a,P->exp);
P=P->next;
Q=Q->next;
}
else if(P->exp>Q->exp){
insert(L,P->a,P->exp);
P=P->next;
}else{
insert(L,Q->a,Q->exp);
Q=Q->next;
}
}
if(!P){
while(P){
insert(L,P->a,P->exp);
P=P->next;
}
}
if(!Q){
while(Q){
insert(L,Q->a,Q->exp);
Q=Q->next;
}
}
return L;
}
int main(){
linkList P,Q,L;
createlinkList(P);
createlinkList(Q);
createlinkList(L);
int n;
cout<<"输入个数"<<endl;
cin>>n;
init(P,n);
cout<<"输入个数"<<endl;
cin>>n;
init(Q,n);
L=uni(Q,P,L);
// L=L->next;
while(L->next){
L=L->next;
if(!L->next)
cout<<L->a<<"X"<<'('<<L->exp<<')';
else cout<<L->a<<"X"<<'('<<L->exp<<')'<<'+';
}
return 0;
}
编写将两个多项式相加的函数。不要毁坏输人数据。用一个链表实现。如果这两个多项式分别有 M 项和N 项,那么你的程序的时间复杂度是多少?
最新推荐文章于 2024-07-13 16:00:03 发布