将数读入链表的基础问题
题目是读入两个多项式,然后做加法,用链表实现。C语言上学期学的,这学期学数据结构,链表几乎忘光,自己看着课本debug不出来……整个程序在这里,但是大侠们帮我解决输入数据后无法正常CreatePoly的问题就好。
比如P1: x+x^2+2x^3, P2:2+3x^2+x^5
#include <stdio.h>
struct Poly{
double coef;
int expt;
struct Poly *next;
};
int size = sizeof(struct Poly);
struct Poly *CreatePoly();
struct Poly *AddPoly(struct Poly *p1, struct Poly *p2);
struct Poly *PrintPoly(struct Poly *head);
main()
{
struct Poly *head1, *head2, *headsum;
head1 = head2 = headsum = NULL;
printf("Polynomial 1\n");
head1 = CreatePoly();
printf("Polynomial 2\n");
head2 = CreatePoly();
if(head1 != NULL && head2 != NULL)
headsum = AddPoly(head1, head2);
PrintPoly(head1);
printf("+");
PrintPoly(head2);
printf("=");
PrintPoly(headsum);
}
struct Poly *CreatePoly()
{
struct Poly *head, *tail, *p;
double coef;
int expt;
printf("Input coefficients & exponents ascendingly. End with the coefficient 0\n");
scanf("%lf%d", &coef, &expt);
head = tail = NULL;
while(1){
p = (struct Poly *) malloc(size); /*调试时是到这里就跳出TC……为什么呢?*/
if(p == NULL){
printf("Memory allocation failure.\n");
return NULL;
}
p->coef = coef;
p->expt = expt;
if(head == NULL){
head = p;
tail = head;
}
else tail->next = p;
tail = p;
scanf("%lf", &coef);
if(coef != 0)
scanf("%d", &expt);
else break;
}
return head;
}
struct Poly *AddPoly(struct Poly *p1, struct Poly *p2)
{
struct Poly *q1, *q2, *head, *tail, *p;
head = tail = NULL;
q1 = p1;
q2 = p2;
do{
if(head == NULL){
p = (struct Poly *) malloc(size);
if(q1->expt < q2->expt){
p->coef = q1->coef;
p->expt = q1->expt;
q1 = q1->next;
}
else if(q1->expt == q2->expt){
p->coef = q1->coef + q2->coef;
p->expt = q1->expt;
q1 = q1->next;
q2 = q2->next;
}
else{
p->coef = q2->coef;
p->expt = q2->expt;
q2 = q2->next;
}
head = p;
tail = head;
}
else{
if(q1->expt < q2->expt || q2 == NULL){
p->coef = q1->coef;
p->expt = q1->expt;
q1 = q1->next;
}
else if(q1->expt == q2->expt){
p->coef = q1->coef + q2->coef;
p->expt = q1->expt;
q1 = q1->next;
q2 = q2->next;
}
else{
p->coef = q2->coef;
p->expt = q2->expt;
q2 = q2->next;
}
tail->next = p;
tail = p;
}
}while(!(q1->next == NULL && q2->next == NULL));
return head;
}
struct Poly *PrintPoly(struct Poly *head)
{
struct Poly *p;
for(p = head; p->next != NULL; p = p->next){
if(p->expt != 0)
printf("%lfx^%d+", p->coef, p->expt);
else printf("%lf+", p->coef);
}
if(p->expt != 0)
printf("%lfx^%d", p->coef, p->expt);
else printf("%lf", p->coef);
}