哪位大侠帮帮我一下~~ 先谢
#include <stdio.h>#include <malloc.h>
#include <stdlib.h>
#define NULL 0
typedef struct pnode {
float coef;
int exp;
struct pnode *next;
}polynode;
pnode *Creat(int n);
void print(pnode *head);
pnode *AddPolyn(pnode *head1, pnode *head2);
pnode *Delfirst(pnode *head, pnode *q);
void InsertBefore(pnode *p1, pnode *p2);
int compare(int a, int b);
pnode *Creat(int n)
{
pnode *current, *previous, *head;
int i;
head = (pnode *)malloc(sizeof(pnode));
previous = head;
for(i = 0; i < n; i++)
{
current = (pnode *)malloc(sizeof(pnode));
printf("请输入系数和指数 : ");
scanf("%f%d", ¤t->coef, ¤t->exp);
previous->next = current;
previous = current;
}
previous->next = NULL;
return head;
}
pnode *AddPolyn(pnode *head1, pnode *head2)
{
pnode *ha, *hb, *qa, *qb;
int a, b;
float sum;
ha = head1;
hb = head2;
qa = ha->next;
qb = hb->next;
while(qa && qb)
{
a = qa->exp;
b = qb->exp;
switch(compare(a, b)) {
case -1 :
ha = qa;
qa = qa->next;
break;
case 0 :
sum = qa->coef + qb->coef;
if(sum != 0.0) {
qa->coef = sum;
ha = qa;
}else {
free(Delfirst(ha, qa));
}
free(Delfirst(hb, qb));
qa = ha->next;
qb = hb->next;
break;
case 1 :
Delfirst(hb, qb);
InsertBefore(ha, qb);
qb = hb->next;
ha = ha->next;
break;
}
}
if(qb)
ha->next = qb;
free(head2);
return head1;
}
int compare(int a, int b)
{
if(a < b)
return -1;
else if(a > b)
return 1;
else
return 0;
}
pnode *Delfirst(pnode *p1,pnode *q)
{
p1 -> next = q -> next;
return (q);
}
void InsertBefore(pnode *p1, pnode *p2)
{
pnode *p;
p = p1->next;
p1->next = p2;
p2->next = p;
}
void print(pnode *head)
{
pnode *current;
current = head->next;
while(current->next != NULL)
{
printf("%0.f * x^%d + ", current->coef, current->exp);
current = current -> next;
}
printf("%0.f * x^%d", current->coef, current->exp);
getchar();
}
int main()
{
pnode *head1, *head2, *head3;
int n1, n2;
printf("请输入你需要的多项数的数目 n1 : ");
scanf("%d", &n1);
head1 = Creat(n1);
printf("第一个多项式的显示 : \n");
print(head1);
printf("\n请输入你需要的多项数的数目 n2 : ");
scanf("%d", &n2);
head2 = Creat(n2);
printf("\n第二个多项式的显示 : \n");
print(head2);
head3 = AddPolyn(head1, head2);
printf("\n合并后的多项式的显示 : \n");
print(head3);
printf("\n");
}
这个是2个多项式相加的程序,为什么我把第二个多项式取反,这样就变成2个多项式相减了。但是运行出错。。。。 那位大侠帮帮忙阿~~~~