首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

离奇的相加有关问题

2012-03-09 
离奇的相加问题大家帮忙看看,想了很久,不知是什么错误。多项式相加,单链表实现。#include stdio.h#include

离奇的相加问题
大家帮忙看看,想了很久,不知是什么错误。多项式相加,单链表实现。

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define   MAXSIZE   10
typedef   struct   lnode
{
double   coef;
int   exp;
struct   lnode   *next;
}lnode;
typedef   struct   data
{
double   coef;
int   exp;
}datamatrix[MAXSIZE];
void   creatlinklist(lnode   *l,datamatrix   a,int   ai)
{
int   i;
lnode   *p=l,*q;
for(i=0;i <ai;i++)
{
if(!(q=(lnode   *)malloc(sizeof(lnode))))
{
puts( "distribute   memery   error. ");
exit(1);
}
q-> coef=a[i].coef,q-> exp=a[i].exp;
p-> next=q,p=q;
}
p-> next=NULL;
}
void   sort(lnode   *l)
{
lnode   *p=l-> next,*q,*r=p-> next;
if(p)
{
r=p-> next;
p-> next=NULL;
p=r;
while(p)
{
r=r-> next;
q=l;
while(q-> next&&q-> next-> exp <p-> exp)
q=q-> next;
p-> next=q-> next;
q-> next=p;
p=r;
}
}
}
void   add(lnode   *ha,lnode   *hb)
{
lnode   *a,*b,*af,*br;
double   c;
af=ha;
a=ha-> next,b=hb-> next;
free(hb);
while(a&&b)
{
if(a-> exp> b-> exp)
{
br=b-> next;
b-> next=a;
af-> next=b;
b=br;
br=br-> next;
af=b;
}
else   if(a-> exp <b-> exp)
{
af=a;
a=a-> next;
}
else   if(a-> exp==b-> exp)
{
c=a-> coef+b-> coef;
if(c==0)
{
af-> next=a-> next;
free(a),free(b);
a=af-> next;
b=br,br=b-> next;
}
else
{
a-> coef=c;
af=a,a=af-> next;
free(b);
b=br,br=b-> next;
}
}
}
if(!a&&b)
a=b;
}
void   displist(lnode   *l)
{
lnode   *p=l-> next;
while(p)
{
printf( "%lfx^%d   ",p-> coef,p-> exp);
p=p-> next;
}
puts( " ");
}
void   main()
{
lnode   *ha,*hb;
datamatrix   a={{2.4,0},{1.0,2},{1.2,3},{5.1,4}};
datamatrix   b={{1.1,0},{2.3,1}.{-1.0,2},{6.2,4},{6.0,8}};
int   ai=2,bi=2;
if(!(ha=(lnode   *)malloc(sizeof(lnode))))
{
puts( "distribute   memery   error. ");
exit(1);
}
if(!(hb=(lnode   *)malloc(sizeof(lnode))))
{
puts( "distribute   memery   error. ");
exit(1);
}
creatlinklist(ha,a,ai);
creatlinklist(hb,b,bi);
puts( "原多项式ha为: ");
displist(ha);
puts( "原多项式hb为: ");
displist(hb);
sort(ha);
sort(hb);
puts( "有序多项式ha为: ");
displist(ha);
puts( "有序多项式hb为: ");
displist(hb);
add(ha,hb);
puts( "相加结果为: ");
displist(ha);
}

运行:
原多项式ha为:
2.400000x^0   1.000000x^2   1.200000x^3   5.100000x^4
原多项式hb为:
1.100000x^0   2.300000x^1   -1.000000x^2   6.200000x^4   6.000000x^8
有序多项式ha为:
2.400000x^0   1.000000x^2   1.200000x^3   5.100000x^4
有序多项式hb为:
1.100000x^0   2.300000x^1   -1.000000x^2   6.200000x^4   6.000000x^8


Press   any   key   to   continue

到底是那里错,请各位指点小弟一下,谢谢。



[解决办法]
先纠正一下lz笔误
datamatrix a={{2.4,0},{1.0,2},{1.2,3},{5.1,4}};
datamatrix b={{1.1,0},{2.3,1},{-1.0,2},{6.2,4},{6.0,8}};
int ai=4,bi=5;

void add(lnode *ha,lnode *hb){
...
while(a&&b)
{
br = b-> next;//最好写在这里,后面的有重复,也有漏的
if(a-> exp> b-> exp)
{
...
b=br;
af=af-> next;//b已经是br了,或者把af=b写在上句前面
}
...
}
if(b)
af-> next = b;//a只是一个局部变量,a=b没有实际意义
}
楼主的代码最好能加点注释说明一下参数用处

热点排行