Write a program to perform addition and multiplication for given two sparse polynomials. Create a node for each term in the given polynomial.
2. Write a program to perform transpose for a given sparse matrix. ( Row major order)
Note: The last date for submission is 03-9-2021
Note: Implementation can be done either in C or C++ for questions 1 and 2.
#include <iostream>
using namespace std;
struct Node {
int co;
int p;
struct Node* next;
};
void create_node(int x, int y, struct Node** temp)
{
struct Node *r, *z;
z = *temp;
if (z == NULL) {
r = (struct Node*)malloc(sizeof(struct Node));
r->co = x;
r->p = y;
*temp = r;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
}
else {
r->co = x;
r->p = y;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
}
}
void polyadd(struct Node* poly1, struct Node* poly2,
struct Node* poly)
{
while (poly1->next && poly2->next) {
if (poly1->p > poly2->p) {
poly->p = poly1->p;
poly->co = poly1->co;
poly1 = poly1->next;
}
else if (poly1->p < poly2->p) {
poly->p = poly2->p;
poly->co = poly2->co;
poly2 = poly2->next;
}
else {
poly->p = poly1->p;
poly->co = poly1->co + poly2->co;
poly1 = poly1->next;
poly2 = poly2->next;
}
poly->next
= (struct Node*)malloc(sizeof(struct Node));
poly = poly->next;
poly->next = NULL;
}
while (poly1->next || poly2->next) {
if (poly1->next) {
poly->p = poly1->p;
poly->co = poly1->co;
poly1 = poly1->next;
}
if (poly2->next) {
poly->p = poly2->p;
poly->co = poly2->co;
poly2 = poly2->next;
}
poly->next
= (struct Node*)malloc(sizeof(struct Node));
poly = poly->next;
poly->next = NULL;
}
}
void show(struct Node* node)
{
while (node->next != NULL) {
printf("%dx^%d", node->co, node->p);
node = node->next;
if (node->co >= 0) {
if (node->next != NULL)
printf("+");
}
}
}
int main()
{
struct Node *poly1 = NULL, *poly2 = NULL, *poly = NULL;
create_node(5, 2, &poly1);
create_node(4, 1, &poly1);
create_node(2, 0, &poly1);
create_node(-5, 1, &poly2);
create_node(-5, 0, &poly2);
printf("First Number: ");
show(poly1);
printf("\nSecond Number: ");
show(poly2);
poly = (struct Node*)malloc(sizeof(struct Node));
polyadd(poly1, poly2, poly);
printf("\nAdded polynomial: ");
show(poly);
return 0;
}
Comments
Leave a comment