I am trying to implement polynomials using linked lists and circular representation i.e. link of the last node pointing to the first node(header). When I create my first polynomial using the function create
all the links get established perfectly, including the last, circular one. However the moment I create a second polynomial using the same function 'create',the circular link of the first polynomial breaks off. (All the other links of the first polynomial remain intact). I'm using the turboC++ compiler (I've saved my file with a .c
extension.)
The create function is as follows:
void create(poly header)
{
poly temp;
int i,n;
temp=header;
printf("\nEnter the number of terms: "); scanf("%d",&n);
if(n==0)
{
header->link=header;
return;
}
printf("\nEnter the coefficients and exponents:\n");
for(i=0;i<n;i++)
{
temp->link=malloc(sizeof(poly));
temp=temp->link;
printf("\nCoef: "); scanf("%d",&temp->coef);
printf("Exp : "); scanf("%d",&temp->exp);
if(i==n-1)
temp->link=header;
}
}
The main function is as follows:
void main()
{
clrscr();
header1=malloc(sizeof(poly));
header2=malloc(sizeof(poly));
printf("Polynomial 1:\n");
create(header1);
printf("\nPolynomial 2:\n");
create(header2);
printf("\n\nP1: ");
display(header1);
printf("\n\nP2: ");
display(header2);
getch();
}
The display function is as follows:
void display(poly header)
{
poly temp;
if(header->link==header)
printf("Zero polynomial\n");
temp=header->link;
while(temp!=header)
{
if(temp->exp==header->link->exp||temp->coef<0)
printf("%d(x^%d)",temp->coef,temp->exp);
else
printf(" + %d(x^%d)",temp->coef,temp->exp);
temp=temp->link;
}
}
Both the functions create
and display
work perfectly; I've checked by creating a single polynomial and printing it.
I have traced the program and checked for the links (I've used the polynomials 3x^2+2x+1 and 2x^2+1 as my first and second polynomials respectively).
This is how I've done the declarations:
struct POLY
{
int coef,exp;
struct POLY *link;
};
typedef struct POLY* poly;
poly header1=NULL,header2=NULL,header3=NULL; //global
My problem may sound trivial but please help me. I'm a novice to using linked lists.