数据结构一元多项式c++加减
时间: 2024-01-01 13:05:00 浏览: 93
以下是一元多项式的C++加减代码示例:
```c++
#include<iostream>
using namespace std;
struct node{
int coef,exp;
node *next;
};
node *create(int n){
node *head,*p,*q;
head=new node;
head->next=NULL;
q=head;
for(int i=1;i<=n;i++){
p=new node;
cin>>p->coef>>p->exp;
p->next=NULL;
q->next=p;
q=p; }
return head;
}
node *add(node *a,node *b){
node *head,*p,*q,*r;
head=new node;
head->next=NULL;
p=a->next;
q=b->next;
r=head;
while(p!=NULL&&q!=NULL){
if(p->exp<q->exp){
r->next=p;
r=p;
p=p->next;
}
else if(p->exp>q->exp){
r->next=q;
r=q;
q=q->next;
}
else{
if(p->coef+q->coef!=0){
p->coef+=q->coef;
r->next=p;
r=p;
}
p=p->next;
q=q->next;
}
}
if(p!=NULL) r->next=p;
if(q!=NULL) r->next=q;
return head;
}
node *sub(node *a,node *b){
node *head,*p,*q,*r;
head=new node;
head->next=NULL;
p=a->next;
q=b->next;
r=head;
while(p!=NULL&&q!=NULL){
if(p->exp<q->exp){
r->next=p;
r=p;
p=p->next;
}
else if(p->exp>q->exp){
q->coef=-q->coef;
r->next=q;
r=q;
q=q->next;
}
else{
if(p->coef-q->coef!=0){
p->coef-=q->coef;
r->next=p;
r=p;
}
p=p->next;
q=q->next;
}
}
while(p!=NULL){
r->next=p;
r=p;
p=p->next;
}
while(q!=NULL){
q->coef=-q->coef;
r->next=q;
r=q;
q=q->next;
}
return head;
}
void print(node *head){
node *p;
p=head->next;
while(p!=NULL){
cout<<p->coef<<" "<<p->exp<<endl;
p=p->next;
}
}
int main(){
int n,m;
node *a,*b,*c,*d;
cin>>n>>m;
a=create(n);
b=create(m);
c=add(a,b);
d=sub(a,b);
print(c);
print(d);
return 0;
}
```
阅读全文