求c多项式相加程序 数据从外部文件读取 牛人赶紧的!!!
有代码如下#include<stdio.h>#include<malloc.h>
typedef struct linklist
{
int coef;//系数
int exp; //指数
struct linklist *next;
}nodelink;
nodelink *create(nodelink *a)//创建单链表
{
nodelink *head,*s,*t;
int c=a->coef,e=a->exp;
head=(nodelink *)malloc(sizeof(nodelink));//哨兵头结点
head->next=NULL;
t=head;//始终指向单链表的尾部
printf("请输入c和e的值,当系数e等于-1为结束条件:\n");
//scanf("%d%d",&c,&e);
while(e!=-1)
{
s=(nodelink *)malloc(sizeof(nodelink));
s->coef=c;
s->exp=e;
s->next=NULL;
t->next=s;
t=s;
printf("请继续输入c和e的值,当系数e等于-1为结束条件:\n");
//scanf("%d%d",&c,&e);
}
return head;
}
void printhead(nodelink *head)//输出连表数据
{ int pcount=1; //结点计数器
nodelink *phead;
phead=head->next; //指向第一个元素结点
while(phead!=NULL)
{
printf("第%d个结点的系数和指数分别为:",pcount);
printf("%2d%4d\n",phead->coef,phead->exp);
phead=phead->next;
pcount++;
}
printf("\n");
}
nodelink *ADD(nodelink *heada,nodelink *headb)//实现多项式相加
{
nodelink *p,*q,*prea,*preb,*temp;
int sum;
p=heada->next;//分别使p和q指向第一个元素结点
q=headb->next;
prea=heada;
free(headb);//释放headb链表的头结点
while(p!=NULL&&q!=NULL)
{
if(p->exp<q->exp)
{
prea=p;
p=p->next;
}
else if(p->exp==q->exp)
{
sum=p->coef+q->coef;
if(sum!=0)
{
p->coef=sum;
preb=q;
prea=p;
p=p->next;
q=q->next;
free(preb);
}
else//如果和为零
{
temp=p;
p=p->next;
prea->next=p;
free(temp);
preb=q;
q=q->next;
free(preb);
}
}
else //若p->exp大于q->exp
{
preb=q;
q=q->next;
preb->next=p;
prea->next=preb;
prea=prea->next;
}
}
if(q!=NULL)
prea->next=q;
return heada;
}
void main()
{ int i,j,m,n;
nodelink *heada,*headb,*headc;
FILE *fp;
fp=fopen("11.txt","r");
fscanf(fp,"%d,%d",&i,&j);heada->coef=&i;heada->exp=&j;
fscanf(fp,"%d,%d",&m,&n);headb->coef=&m;headb->exp=&n;
heada=create(heada);
printhead(heada);
headb=create(headb);
printhead(headb);
headc=ADD(heada,headb);
printf("相加后的的链表为:\n");
printhead(headc);
}
我表示达不到目的 谁能帮忙改改?
[ 本帖最后由 zq_16 于 2011-3-26 19:16 编辑 ]