单链表求和一元多项式 程序检查很多遍都一直不对
#include<string.h>
#include<ctype.h>
#include<malloc.h>
#include<limits.h>
#include<stdio.h>
#include<stdlib.h>
#include<io.h>
#include<math.h>
#include<process.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
typedef int Status;
typedef struct
{
float coef;//系数
int expn;//指数
}term,ElemType;
typedef struct LNode//定义结点类型
{
ElemType data;
struct LNode *next;
}*Link,*Position;
typedef struct//链表类型
{
Link head,tail;
int len;
}LinkList;
Status InitList(LinkList &L)//初始化,建立一个空的一元多项式链表
{
L.head=(Link)malloc(sizeof(struct LNode));
if(!L.head)
exit(OVERFLOW);
L.tail=L.head;
L.len=0;
L.head->next=NULL;
return OK;
}
void create(LinkList &L,int m)//输入一元多项式
{
Link p=L.head;
Link q;
L.len=m;
for(int i=0;i<L.len;i++)
{
q=(Link)malloc(sizeof(struct LNode));
printf("请输入第%d的系数",i+1);
scanf("%f",&q->data.coef);
printf("请输入第%d的指数",i+1);
scanf("%d",&q->data.expn);
q->next=p->next;
p->next=q;
}
}
void show(LinkList L) //输出
{
Link p=L.head;
printf("\n下面输出此一元多项式:\n");
while(p->next)
{
p=p->next;
printf("%.2fx^%d\t",p->data.coef,p->data.expn);
}
}
int compare(int a,int b)//比较函数
{
if(a==b) return 1;
else return 0;
}
Status add(LinkList &L,LinkList &K)//相加
{
Link p=L.head;
Link q=K.head;
Link t;
L.len=L.len+K.len;
while(q->next)
{
t=(Link)malloc(sizeof(struct LNode));
q=q->next;
t->data.coef=q->data.coef;
t->data.expn=q->data.expn;
t->next=p->next;
p->next=t;
}//合二为一
show(L);
Link d;
d=L.head;
while(d->next)
{
d=d->next;
printf("%d",d->data.expn);
}
Link x;
Link y;
x=L.head;
while(x->next)
{
x=x->next;
y=x;
while(y->next)
{
y=y->next;
if(x->data.expn==y->data.expn)
{
x->data.coef+=y->data.coef;
free(y);
}
}
}
return OK;
}
void main()
{
LinkList L;
LinkList K;
InitList(L);
InitList(K);
printf("请输入L的一元多项式的个数:");
int a,b;
scanf("%d",&a);
create(L,a);
printf("请输入K的一元多项式的个数:");
scanf("%d",&b);
create(K,b);
show(L);
show(K);
add(L,K);
show(L);
}
这个程序反复改了很多次,一直在
while(x->next)
{
x=x->next;
y=x;
while(y->next)
{
y=y->next;
if(x->data.expn==y->data.expn)
{
x->data.coef+=y->data.coef;
free(y);
}
}
}
这块地方出问题,不明白是为什么;