Click here to Skip to main content
12,953,379 members (49,249 online)
Rate this:
 
Please Sign up or sign in to vote.
See more:
i performed polynomial multiplication.but the results contains more than one node with same degree.

eg:(4x^3+2x^2+1)(2x^2+2) -> 8x^5 +8x^3 +4x^4 +4x^2 + 2x^2 +2
but i want the result as -> 8x^5 +8x^3 +4x^4 +6x^2 + 2 (ie to sum the nodes with same degree).


For that i coded as below.it performs well for smaller expressions.but when i give the expression above as input it produces the result as
8x^5 +8x^3 +4x^4 +6x^2

The last element is not displaying.i again and again corrected the for loop limits.but that doesn't help.why the last element not displaying?somebody plz help.......

/*startmul points to multiplied result linked list.startaddmul is for the final linked list*/
for(tempmul=startmul;tempmul!=NULL;tempmul=tempmul->next)
{
  if(startaddmul==NULL)
  {
    newnode=malloc(sizeof(struct node));
    newnode->coef=tempmul->coef;
    newnode->deg=tempmul->deg;
    newnode->next=NULL;
    startaddmul=newnode;
  }
  else
  {
    for(temp=startaddmul;temp!=NULL;temp=temp->next)
    {
      if(temp->deg==tempmul->deg)
      {
        temp->coef+=tempmul->coef;
        flag=1;
      }
    }
    if(flag!=1)
    {
      for(temp=startaddmul;temp->next!=NULL;temp=temp->next)
        ;
      newnode=malloc(sizeof(struct node));
      newnode->coef=tempmul->coef;
      newnode->deg=tempmul->deg;
      newnode->next=NULL;
      temp->next=newnode;
    }
  }
}
}


Edit: formatted code - Avi Berger
Posted 2-Mar-10 5:11am
Updated 2-Mar-10 11:16am
v3

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Hi your code is right. You made a small logical mistake.. You forget to clear flag. I tried your code as it is with flag reset. It worked well.

if(flag!=1)
    {
      for(temp=startaddmul;temp->next!=NULL;temp=temp->next)
        ;
      newnode=malloc(sizeof(struct node));
      newnode->coef=tempmul->coef;
      newnode->deg=tempmul->deg;
      newnode->next=NULL;
      temp->next=newnode;
    }
else
{
    flag = 0;
}
  Permalink  
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    Print Answers RSS
Top Experts
Last 24hrsThis month
OriginalGriff 6,429
CHill60 3,490
Maciej Los 3,103
Jochen Arndt 1,975
ppolymorphe 1,920


Advertise | Privacy | Mobile
Web01 | 2.8.170525.1 | Last Updated 24 Dec 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100