It’s a very simple problem and I have written it for about 3 times. This time, I finished the program successfully without any mistake in creating list, inserting a node or printing the list. But when I excuted it in Xcode, something went wrong - I forget to use ‘&’. Add to it? Xcode doesn’t support the use of ‘&’. So, very unwillingly, I changed the type of the functions.
And my code …
#include <stdio.h>
#include <stdlib.h>
typedef struct Node *PtrToNode;
struct Node{
int exp;
float coe;
PtrToNode next;
};
typedef PtrToNode List;
typedef PtrToNode Position;
int alen = -1, blen = -1, len;
List CreateList();
List Insert(int exp, float coe, List L, Position P);
void PrintList(List L, int ListLength);
int main()
{
// La + Lb => La
List La, Lb;
Position pa, pb, pP;
// Initiate La, Lb
La = CreateList();
Lb = CreateList();
pa = La->next;
pb = Lb->next;
// La + Lb
while (pa && pb)
{
if (pa->exp > pb->exp)
pa = pa->next;
else if (pa->exp < pb->exp)
{
Insert(pb->exp, pb->coe, La, pa); // Insert the node in front of pa
alen++;
pb = pb->next;
}
else
{
pa->coe = pa->coe + pb->coe;
if(pa->coe == 0)
{
pP = La;
while(pP->next != pa)
pP = pP->next;
pP->next = pa->next;
pa = pP;
alen--;
} // Forget to consider the case when the coefficient after add = 0
pa = pa->next;
pb = pb->next;
}
}
if(pb)
while(pb)
{
Insert(pb->exp, pb->coe, La, NULL);
pb = pb->next;
alen++;
}
// print La
PrintList(La, alen);
return 0;
}
List CreateList()
{
int length, i = 0;
PtrToNode a, p;
List L;
L = (List)malloc(sizeof(struct Node));
L->next = NULL;
p = L;
scanf("%d", &length);
if (alen == -1)
alen = length;
else blen = length;
while (i < length)
{
a = (PtrToNode)malloc(sizeof(struct Node));
scanf(" %d %f", &a->exp, &a->coe); // add a ' ' here and '.' can be successfully read in
a->next = p->next;
p->next = a;
p = a;
i++;
}
return L;
}
List Insert(int exp, float coe, List L, Position P)
{
PtrToNode a, pP = L;
a = (PtrToNode)malloc(sizeof(struct Node));
a->exp = exp;
a->coe = coe;
while (pP->next != P)
pP = pP->next;
a->next = pP->next;
pP->next = a;
return L;
}
void PrintList(List L, int ListLength)
{
PtrToNode p = L->next;
printf("%d", ListLength);
while(p)
{
printf(" %d %.1f", p->exp, p->coe);
p = p->next;
}
}
And how to multiply two polynomials?