问题描述
- C语言 多项式加法中的问题
-
不知道结果为什么出错,怎么也找不出来
#include
#includestruct PolyNode{
int coef; //系数
int expon; //指数
struct PolyNode *link;//指向下一个节点的指针};
typedef struct PolyNode *Polynomial;
Polynomial P1, P2, P3, P4,P5;void Attach(int c, int e, Polynomial *pRear)
{
Polynomial P;
P = (Polynomial)malloc(sizeof(struct PolyNode));
P->coef = c;
P->expon = e;
P->link = NULL;
(*pRear)->link = P;
*pRear = P;
}
int Commpare(int a, int b)
{
if (a>b)
return 1;
else if (a == b)
return 0;
else
return -1;
}
Polynomial PolyAdd(Polynomial P1, Polynomial P2)
{
Polynomial front, rear, temp;
int sum;
rear = (Polynomial)malloc(sizeof(struct PolyNode));
front = rear;
while (P1&&P2)
{
switch (Commpare(P1->expon, P2->expon)){
case 1:
Attach(P1->coef, P1->expon, &rear);
P1 = P1->link;
break;
case -1:
Attach(P2->coef, P2->expon, &rear);
P2 = P2->link;
break;
case 0:
sum = P1->coef + P2->coef;
if (sum)Attach(sum, P1->expon, &rear);
P1 = P1->link;
P2 = P2->link;
break;
}
for (; P1; P1 = P1->link)Attach(P1->coef, P1->expon, &rear);
for (; P2; P2 = P2->link)Attach(P2->coef, P2->expon, &rear);
rear->link = NULL;
temp = front->link;
free(temp);
return front;
}
printf("wrong!");
}
main()
{
P2 = (Polynomial)malloc(sizeof(struct PolyNode));
P2->coef = 1;
P2->expon = 1;
P2->link = NULL;P1 = (Polynomial)malloc(sizeof(struct PolyNode)); P1->coef = 2; P1->expon = 2; P1->link = P2; P4 = (Polynomial)malloc(sizeof(struct PolyNode)); P4->coef = 1; P4->expon =1; P4->link = NULL; P3 = (Polynomial)malloc(sizeof(struct PolyNode)); P3->coef = 2; P3->expon = 2; P3->link =P4; P5 = (Polynomial)malloc(sizeof(struct PolyNode)); P5 = PolyAdd(P1, P3); while (P5!=NULL) { printf("%dX%d ", P5->coef, P5->expon); P5=P5->link; }
}
解决方案
多项式加法(单链表 c语言)
多项式相加(C语言)
C语言一元多项式相加问题
解决方案二:
程序太长我没仔细看
不过typedef struct PolyNode *Polynomial;
struct PolyNode{
应该放在int coef; //系数
int expon; //指数struct PolyNode *link;//指向下一个节点的指针
};
之前