/*在使用单链表测试时有部分数据出错,不知道哪里有问题,烦请看一下代码,或者说一下应该测试哪几类特殊数据?
再者使用顺序表方法(代码未贴,且已通过测试)进行时,用时反而少,请问单链表适用于哪里,会显示出它的优点?*/
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef struct{
int expn;//指数
double coef;//系数
}term,ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
typedef LinkList polynomial;
void CreatPolyn(polynomial &p,int m);
void PrintPolyn(polynomial p);
void AddPolyn(polynomial &pa,polynomial &pb);//pa=pa+pb,并销毁一元多项式pb
int main(){
polynomial pa,pb;
int ma,mb;
scanf("%d",&ma);//输入多项式的个数
CreatPolyn(pa,ma);
scanf("%d",&mb);
CreatPolyn(pb,mb);
AddPolyn(pa,pb);由于题目要求输入数据是按顺序排列的,就没有进行排序处理
PrintPolyn(pa);
return 0;
}
void CreatPolyn(polynomial &p,int m){
polynomial q,rear;
rear=(polynomial)malloc(sizeof(LNode));
p=rear;
rear->data.coef=rear->data.expn=0;
rear->next=NULL;
for(int i=0;i<m;i++){
q=(polynomial)malloc(sizeof(LNode));
scanf("%d %lf",&(q->data.expn),&(q->data.coef));
rear->next=q;
rear=q;
rear->next=NULL;
}
}
void PrintPolyn(polynomial p){
polynomial q;
q=p->next;
int count=0;
while(q){
count++;
q=q->next;
}
printf("%d",count);
q=p->next;
while(q){
printf(" %d %.2lf",q->data.expn,q->data.coef);
q=q->next;
}
printf("\n");
free(q);
q=NULL;
}
void AddPolyn(polynomial &pa,polynomial &pb){
polynomial qa,qb,rear;
rear=pa;
qa=pa->next;qb=pb->next;
while(qa&&qb){
if(qa->data.expn>qb->data.expn){
rear->next=qa;
rear=qa;
qa=qa->next;
}
else if(qa->data.expn<qb->data.expn){
rear->next=qb;
rear=qb;
qb=qb->next;
}
else{
if((qa->data.coef+qb->data.coef)){
qa->data.coef+=qb->data.coef;
rear->next=qa;
rear=qa;
}
qa=qa->next;
qb=qb->next;
}
}
while(qa){
rear->next=qa;
rear=qa;
qa=qa->next;
}
while(qb){
rear->next=qb;
rear=qb;
qb=qb->next;
}
free(pb);
pb=NULL;
}
目前暂无任何回答
- 0 回答
- 0 关注
- 2054 浏览
添加回答
举报
0/150
提交
取消