I want to add two polynomials using linked lists. But after entering the second polynomial in 2nd linked list i'm getting a segmentation fault.
when i tried to print the polynomial 1 the powers remain 1 itself but aren't incrementing. Was trying for all possible errors , so code might be little clumsy.
#include<bits/stdc++.h>
using namespace std;
struct node{
int coef;
int po;
node *next;
}*start1=NULL,*go,*go2,*start2=NULL;
int main()
{
int d1,d2;
cout<<"Enter degree of poly 1 :";
cin>>d1;
cout<<"Enter degree of poly 2 :";
cin>>d2;
int i,c,p;
cout<<"Polynomial 1:" ;
for(i=0;i<=d1;i++)
{ p=1;
cout<<"Enter coeff of po "<<i<<" : " ;
cin>>c;
node *temp=new node;
temp->po=p;
p=p+1;
temp->coef=c;
temp->next=NULL;
go=start1;
if(start1==NULL)
{
start1=temp;
continue;
}
while ((go->next)!=NULL)
{
go=go->next;
}
go->next=temp;
p=p+1;
}
cout<<"Polynomial 2 :";
for(i=0;i<=d2;i++)
{ p=1;
cout<<"Enter coeff of po "<<i<<" :";
cin>>c;
node *temp2=new node;
temp2->po=p;
temp2->coef=c;
temp2->next=NULL;
go2=start2;
if(start2==NULL)
{
start2=temp2;
continue;
}
while ((go2->next)!=NULL)
{
go2=go2->next;
cout<<"kk";
}
go2->next=temp2;
p=p+1;
}
go=start1;
while(go!=NULL)
{
go2=start2;
while(go2->next !=NULL)
{
if((go->po)==(go2->po))
{
go->coef = go->coef + go2->coef;
}
go2=go2->next;
}
go=go->next;
}
go=start1;
cout<<"Resultant Polynomial : ";
for(i=0;i<=d1;i++)
{
cout<<go->coef<<"^"<<i+1<<" + ";
go=go->next;
}
i expected the powers to be increasing but it is left as 1 and im getting a segmentation fault