Batch - B Practical Test Question

Batch - B Practical Test Question
Batch - B Practical Test Question

Polynomial Addition Batch - B

#include<stdio.h>
#include<stdlib.h>
#include<memory.h>

struct Node
{
int value;
int pw;
struct Node *next;
};

struct Node *First=NULL,*Second=NULL,*Third=NULL,*temp=NULL,*head=NULL;

struct Node * createLL(int);
void printLL(struct Node *);
struct Node * additionOfLL(struct Node *, struct Node *);

int main()
{
int highpw;

printf("\n Enter Highest power for Polynomial - 1 : ");
scanf("%d",&highpw);
First=createLL(highpw);

head=First;
printLL(head);

printf("\n Enter Highest power for Polynomial - 2 : ");
scanf("%d",&highpw);
Second=createLL(highpw);

head=Second;
printLL(head);

Third=additionOfLL(First,Second);
head=Third;
printf("\n Addition = \n ");
printLL(head);

return 0;
}

void printLL(struct Node *head)
{
while(head!=NULL)
{
printf("%d X^%d -> ",head->value,head->pw);
head=head->next;
}
}

struct Node * createLL(int no)
{
struct Node *myFirst=NULL;
int i=0;
while(i<=no)
{
temp=(struct Node *)malloc(sizeof(struct Node)*1);
temp->pw=i;
temp->next=NULL;
printf("\n Enter Co-efficient of __X^%d : ",i);
scanf("%d",&temp->value);

if(myFirst==NULL)
{
myFirst=temp;
}
else
{
temp->next=myFirst;
myFirst=temp;
}
i++;
}
return myFirst;
}

struct Node * additionOfLL(struct Node *One, struct Node *Two)
{
struct Node *Three=NULL;
struct Node *head1=NULL,*head2=NULL;
head1=One;
head2=Two;

while(head1!=NULL && head2!=NULL)
{
temp=(struct Node *)malloc(sizeof(struct Node)*1);
temp->next=NULL;

if(head1->pw > head2->pw)
{
temp->pw=head1->pw;
temp->value=head1->value;

head1=head1->next;
}
else if(head1->pw < head2->pw)
{
temp->pw=head2->pw;
temp->value=head2->value;

head2=head2->next;
}
else
{
temp->pw=head1->pw;
temp->value=head1->value + head2->value;

head1=head1->next;
head2=head2->next;
}
//To Attach Node in New LL
if(Three==NULL)
{
Three=temp;
}
else
{
head=Three;
while(head->next!=NULL)
{
head=head->next;
}
head->next=temp;
}
}
return Three;
}

Comments