放一下关于一元稀疏多项式-链表版 与去年的一元稀疏多项式·数组版(点击跳转)构成联动
我的代码:
#include<bits/stdc++.h>
using namespace std;
typedef struct Node{
double data_coef;
int data_expn;
Node *next;
}Node,*LinkList;
int list_empty(LinkList &L){
if(L)return 0;
else return 1;
}
void show_list(LinkList &L){
cout<<"[list]:"<<endl;
if(list_empty(L)){
cout<<"Empty!"<<endl;
return;
}else{
LinkList p;
p=L->next;
while(p!=NULL){
cout<<"coef: "<<p->data_coef<<" expn: "<<p->data_expn<<endl;
p=p->next;
}
}
}
void read(LinkList &L,int num){
int n;
LinkList p;
cout<<"【Please input the items of poly】:";
cin>>n;
while(n--){
p=(LinkList)malloc(sizeof(Node));
cin>>p->data_coef>>p->data_expn;
if(num==0)p->data_coef=-p->data_coef;
p->next=L->next;
L->next=p;
}
show_list(L);
}
void read_result_list(LinkList &L){
LinkList p=new Node;
p=L->next;
cout<<"[list]:";
if(list_empty(p)){
cout<<"Empty!"<<endl;
return;
}else{
if(p->data_expn==0)cout<<p->data_coef;
else if(p->data_expn==1)cout<<p->data_coef<<"X";
else cout<<p->data_coef<<"X^"<<p->data_expn;
p=p->next;
while(p){
if(p->data_coef>0)cout<<"+";
if(p->data_expn==0)cout<<p->data_coef;
else if(p->data_expn==1)cout<<p->data_coef<<"X";
else cout<<p->data_coef<<"X^"<<p->data_expn;
p=p->next;
}
}
}
void deal(LinkList &A,LinkList &B){
LinkList qa;
LinkList qb;
LinkList qc;
qc=A;
qa=A;
qb=B->next;
while(qa&&qb){
if(qa->next&&qa->next->data_expn<qb->data_expn){
qc=qb->next;
qb->next=qa->next;
qa->next=qb;
qa=qa->next;
qb=qc;
continue;
}
if(qa->next&&qa->next->data_expn>qb->data_expn){
qa=qa->next;continue;
}
if(qa->data_expn==qb->data_expn){
double sum=0;
sum=qa->data_coef + qb->data_coef;
if (sum==0){
LinkList s=new Node;s=qa;qa=qa->next;free(s);
s=qb;qb=qb->next;free(s);
}else{
qa->data_coef=sum;;
qa=qa->next;
LinkList s=new Node;
s=qb;qb=qb->next;free(s);
}
continue;
}
}
if(qb)qa->next=qb;
free(B);
}
int main(){
LinkList a=new Node;
a->next=NULL;
LinkList b=new Node;
b->next=NULL;
int num;
cout<<"welcome use."<<endl;
cout<<"【add】 - 1"<<endl<<"【minus】 - 0"<<endl<<"【PLS input:】";
cin>>num;
read(a,1);
read(b,num);
deal(a,b);
read_result_list(a);
return 0;
}
|