Develop a Program in C for the following operationson Singly Circular Linked List (SCLL)
with header nodes
a. Represent and Evaluate a Polynomial P(x,y,z) = 6x
2
y
2
z-4yz
5
+3x
3
yz+2xy
5
z-2xyz
3
b. Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z) and store the
result in POLYSUM(x,y,z)
Support the program with appropriate functions for each of the above operations.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct node {
int x, y, z, coeff;
struct node *link;
} *NODE;
NODE getNode() {
NODE temp = (NODE)malloc(sizeof(struct node));
temp->link = temp;
return temp;
}
NODE insertEnd(NODE head, int x, int y, int z, int c) {
NODE temp = getNode();
temp->x = x; temp->y = y; temp->z = z; temp->coeff = c;
if (head->link == head) {
head->link = temp;
temp->link = head;
} else {
NODE cur = head->link;
while (cur->link != head)
cur = cur->link;
cur->link = temp;
temp->link = head;
}
return head;
}
void display(NODE head) {
NODE temp = head->link;
if (temp == head) {
printf("Polynomial is empty.\n");
return;
}
while (temp != head) {
printf("%+dx^%dy^%dz^%d ", temp->coeff, temp->x, temp->y, temp->z);
temp = temp->link;
}
printf("\n");
}
int evaluate(NODE head, int x, int y, int z) {
int sum = 0;
NODE temp = head->link;
while (temp != head) {
sum += temp->coeff * pow(x, temp->x) * pow(y, temp->y) * pow(z, temp->z);
temp = temp->link;
}
return sum;
}
NODE addPoly(NODE p1, NODE p2) {
NODE result = getNode();
NODE t1 = p1->link, t2;
while (t1 != p1) {
insertEnd(result, t1->x, t1->y, t1->z, t1->coeff);
t1 = t1->link;
}
t2 = p2->link;
while (t2 != p2) {
NODE r = result->link;
int found = 0;
while (r != result) {
if (r->x == t2->x && r->y == t2->y && r->z == t2->z) {
r->coeff += t2->coeff;
found = 1;
break;
}
r = r->link;
}
if (!found)
insertEnd(result, t2->x, t2->y, t2->z, t2->coeff);
t2 = t2->link;
}
return result;
}
int main() {
NODE P = getNode();
// a. Representing P(x,y,z) = 6x^2y^2z - 4yz^5 + 3x^3yz + 2xy^5z - 2xyz^3
insertEnd(P, 2,2,1,6);
insertEnd(P, 0,1,5,-4);
insertEnd(P, 3,1,1,3);
insertEnd(P, 1,5,1,2);
insertEnd(P, 1,1,3,-2);
printf("Polynomial P(x,y,z):\n");
display(P);
int x=1, y=2, z=1;
printf("Evaluated at x=%d y=%d z=%d: %d\n", x, y, z, evaluate(P, x, y, z));
// b. Add two polynomials
NODE POLY1 = getNode();
insertEnd(POLY1, 1, 1, 1, 2);
insertEnd(POLY1, 0, 1, 1, 3);
NODE POLY2 = getNode();
insertEnd(POLY2, 1, 1, 1, 4);
insertEnd(POLY2, 2, 1, 0, 5);
NODE POLYSUM = addPoly(POLY1, POLY2);
printf("\nPOLY1:\n"); display(POLY1);
printf("POLY2:\n"); display(POLY2);
printf("POLY1 + POLY2:\n"); display(POLYSUM);
return 0;
}
Polynomial P(x,y,z):
+6x^2y^2z^1 -4x^0y^1z^5 +3x^3y^1z^1 +2x^1y^5z^1 -2x^1y^1z^3
Evaluated at x=1 y=2 z=1: 82
POLY1:
+2x^1y^1z^1 +3x^0y^1z^1
POLY2:
+4x^1y^1z^1 +5x^2y^1z^0
POLY1 + POLY2:
+6x^1y^1z^1 +3x^0y^1z^1 +5x^2y^1z^0
Replay !
Share Your Thoughts