Sunday 15 September 2013

c - When I implement polynomials using linked lists and circular representation the circular link breaks off. Can any one tell me why? -



c - When I implement polynomials using linked lists and circular representation the circular link breaks off. Can any one tell me why? -

i trying implement polynomials using linked lists , circular representation i.e. link of lastly node pointing first node(header). when create first polynomial using function create links established perfectly, including last, circular one. moment create sec polynomial using same function 'create',the circular link of first polynomial breaks off. (all other links of first polynomial remain intact). i'm using turboc++ compiler (i've saved file .c extension.)

the create function follows:

class="lang-c++ prettyprint-override">void create(poly header) { poly temp; int i,n; temp=header; printf("\nenter number of terms: "); scanf("%d",&n); if(n==0) { header->link=header; return; } printf("\nenter coefficients , 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 follows:

class="lang-c++ prettyprint-override">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 follows:

class="lang-c++ prettyprint-override">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 functions create , display work perfectly; i've checked creating single polynomial , printing it.

i have traced programme , checked links (i've used polynomials 3x^2+2x+1 , 2x^2+1 first , sec polynomials respectively).

this how i've done 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 please help me. i'm novice using linked lists.

if poly pointer type malloc()s allocating wrong amount of memory. – john bollinger

i replaced 'poly' 'struct poly' in malloc()'s , got desired output. – arjun desai

c linked-list circular-reference turboc++ polynomials

No comments:

Post a Comment