编写了一个动态链表实现多项式相加出现问题,求大神帮忙(本人新手)
#include<stdio.h>#include<malloc.h>
#include<math.h>
#define LEN sizeof(struct polynomial)
int i,j;
struct polynomial //多项式单个式子的结构体
{
int coff;
int index;
struct polynomial* next;
};
void main() //主函数
{
struct polynomial* create();
void print(struct polynomial* h);
struct polynomial* add(struct polynomial* m,struct polynomial* n);
struct polynomial *head1; //第一个多项式头指针
struct polynomial *head2; //第二个多项式头指针
struct polynomial *headadd; //加法计算过之后多项式头指针
printf("输入第一个多项式:\n");
head1=create();
printf("第一个多项式为:\n");
print(head1);
printf("输入第二个多项式:\n");
head2=create();
printf("第二个多项式为:\n");
print(head2);
printf("进行加法运算:\n");
headadd=add(head1,head2);
printf("加法运算结果为:\n");
print(headadd);
}
struct polynomial* create() //动态链表创建函数
{
int n=0;
struct polynomial *head,*p1,*p2;
p1=p2=(struct polynomial*)malloc(LEN); //分配LEN空间
scanf("%d %d",&p1->coff,&p1->index);
head=NULL;
while(p1->coff!=0) //手动输入0结束此循环(多项式输入结束标志)
{
n++;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct polynomial*)malloc(LEN);
scanf("%d %d",&p1->coff,&p1->index);
}
p2->next=NULL; //标志动态链表到此结束
return(head);
}
void print(struct polynomial *h) //链表输出函数
{
struct polynomial* p;
p=h; //保存链表头指针
while(p->next!=NULL)
{
printf("%dx^%d+",p->coff,p->index);
p=p->next;
if(p->next==NULL)
printf("%dx^%d",p->coff,p->index);
}
printf("\n");
}
struct polynomial* add(struct polynomial* m,struct polynomial* n) //加法运算
{
struct polynomial *p1,*p2;
struct polynomial *top,*end,*head;
head=top=end=(struct polynomial*)malloc(LEN);
p1=m; //保存链表头指针
p2=n;
while(p1->next!=NULL)
{
while(p2->next!=NULL)
{
if(p1->index>p2->index)
{
top->index=p1->index;
top->coff=p1->coff+p2->coff;
top=(struct polynomial*)malloc(LEN);
end->next=top;
p2=p2->next;
continue;
}
if(p1->index<p2->index)
{
top->index=p1->index;
top->coff=p1->coff+p2->coff;
top=(struct polynomial*)malloc(LEN);
end->next=top;
p2=p2->next;
break;
}
if(p1->index==p2->index)
{
top->index=p1->index;
top->coff=p1->coff+p2->coff;
top=(struct polynomial*)malloc(LEN);
end->next=top;
p2=p2->next;
break;
}
}
p1=p1->next;
if(p1->next==NULL)
{
while(p2->next!=NULL) //多项式二大于多项式一
{
top->index=p1->index;
top->coff=p1->coff+p2->coff;
top=(struct polynomial*)malloc(LEN);
end->next=top;
p2=p2->next;
}
}
end->next=NULL;
}
return(head);
}