链表实现多项式求和(C语言)0
aebgt2013.06.26浏览270次分享举报
1 多项式求和中两个链表合并问题,请各位大侠帮忙啊
#include
#include
typedef struct node
{
float coef;
int exp;
struct node *next;
}link,*linklist;
linklist creatployn ()
{
linklist head,temp,now;
temp=now=(linklist)malloc(sizeof(link));
printf("请输入该项系数和指数:\n");
scanf("%f,%d",&temp->coef,&temp->exp);
temp->next=NULL;
if (temp->coef==0.0||temp->exp<0)
{
head=NULL;
free(now);
}
else head=now;
while (temp->coef!=0.0&&temp->exp>=0)//
{
now->next=temp;
now=temp;
temp=(linklist)malloc(sizeof(link));
printf("请输入该项系数和指数:\n");
scanf("%f,%d",&temp->coef,&temp->exp);
}
free(temp);
now->next=NULL;
return(head);
}
void printployn(linklist head)
{
linklist p=head;
int n=1;
printf("该表达式为:\n");
if(p==NULL)
return;
while(p!=NULL)
{
if(n==1) {printf("%fX^%d",p->coef,p->exp); n++;}
else printf("+%fX^%d",p->coef,p->exp);
p=p->next;
}
}
int compare(int x,int y) //比较两个多项式的指数
{
if(x
else if(x=y) return 0;
else return 1;
}
linklist addployn(linklist la,linklist lb) //两个多项式的合并(此处在la表上与lb表对应元素作比较,做出响应的添加删除操作,最后返回la)
{
linklist head,temp=(linklist)malloc(sizeof(link)),qa=la,qb=lb,tempa,tempb;
head=temp;
temp->next=NULL;
int a,b;
while(qa&&qb)
{
a=qa->exp; b=qb->exp;
switch (compare(a,b))
{
case -1:
temp->next=qa; temp=qa; qa=qa->next;break;//将la表的结点作为当前结点,并将la指向la表当前结点的下一结点
case 0: //合并指数相同的项
qa->coef+=qb->coef; //系数相加
if(qa->coef!=0) //系数不为零,将la表的结点作为当前结点,并释放lb表结点,再分别让qa,qb指向各自的下一结点
{
temp->next=qa;//
temp=qa;
qa=qa->next;
}
else //系数为零将当前la,lb表重的结点释放,并指向各自的下一点
{
tempa=qa;
qa=qa->next;
free(tempa);
}
tempb=qb; qb=qb->next; free(tempb);
break;
case 1:
temp->next=qb; temp=qb; qb=qb->next; //将lb表结点插入la表作为当前结点,并使qb指向下一结点
break;
}
}
if(qa) temp->next=qa;
else temp->next=qb;
tempa=head;
head=head->next;
free(tempa);
return(head);
}
void main()
{
linklist LA=creatployn();
printployn(LA);
linklist LB=creatployn();
printployn(LB);
linklist LC=addployn(LA,LB);
printployn(LC);
}
基本思路是按指数从小到大输入系数和指数,到0,0结束该多项式输入。求和部分,不引入新表,而在原来的a表上将b表元素进行插入和删除的操作。
我对链表操作概念很不清楚。在求和函数中的temp必须要给他申请空间么?我最初就把temp设成普通指针变量,通过移动他的位置来指向当前结点,但是好像链表一点都没链起来。麻烦哪位好心人能帮我详细解释一下这个链接的过程啊:)不胜感激啊!
讲的详细我追加分数!关于链表的问题已经困扰我很久了。期待高人点拨迷津~~~