C program to add two polynomial | SLL | C Program

 C program to add two polynomial | SLL

 #include<stdio.h>

#include<stdlib.h>

 typedef struct link {
 int coef;
 int exp;
 struct link * next;
 } my_poly;

 void my_create_poly(my_poly **);

 void my_show_poly(my_poly *);

 void my_add_poly(my_poly **, my_poly *, my_poly *);

 int main(void) {
 int ch;

 my_poly * poly1, * poly2, * poly3;

 printf("\n\t\t**** Create 1st expression ****\n");

 my_create_poly(&poly1);

 printf("\n\t\t* 1st expression Stored *");

 my_show_poly(poly1);

 printf("\n\n\t\t**** Create 2nd expression ****\n");

 my_create_poly(&poly2);

 printf("\n\t\t** 2nd expression Stored **");

 my_show_poly(poly2);

 my_add_poly(&poly3, poly1, poly2);

 my_show_poly(poly3);

 getch();
 return 0;
 }

 void my_create_poly(my_poly ** node) {

 int flag; //A flag to control the menu
 int coef, exp;

 my_poly * tmp_node;

 tmp_node = (my_poly *) malloc(sizeof(my_poly)); //create the first node
 *node = tmp_node;

 do {

 printf("\n\tEnter Coefficient and Exponent respectively: ");
 scanf("%d%d", &coef, &exp);

 tmp_node->coef = coef;
 tmp_node->exp = exp;
 tmp_node->next = NULL;

 printf("Continue adding more terms to the polynomial list?(Yes = 1/No = 0): ");
 scanf("%d", &flag);

 if(flag) {
 tmp_node->next = (my_poly *) malloc(sizeof(my_poly)); //Grow the list
 tmp_node = tmp_node->next;
 tmp_node->next = NULL;
 }
 } while (flag);
 }

 void my_show_poly(my_poly * node) {
 printf("\nThe polynomial expression is:\n\t\t\t\tP(x) = ");
 while(node != NULL) {
 printf("%dx^%d", node->coef, node->exp);
 node = node->next;
 if(node != NULL)
 printf(" + ");
 }
 }
 void my_add_poly(my_poly ** result, my_poly * poly1, my_poly * poly2) {
 my_poly * tmp_node;
 tmp_node = (my_poly *) malloc(sizeof(my_poly));
 tmp_node->next = NULL;
 *result = tmp_node; //Copy the head address to the result linked list

 while(poly1 && poly2) {
 if (poly1->exp > poly2->exp) {
 tmp_node->exp = poly1->exp;
 tmp_node->coef = poly1->coef;
 poly1 = poly1->next;
 }
 else if (poly1->exp < poly2->exp) {
 tmp_node->exp = poly2->exp;
 tmp_node->coef = poly2->coef;
 poly2 = poly2->next;
 }
 else {
 tmp_node->exp = poly1->exp;
 tmp_node->coef = poly1->coef + poly2->coef;
 poly1 = poly1->next;
 poly2 = poly2->next;
 }

 if(poly1 && poly2) {
 tmp_node->next = (my_poly *) malloc(sizeof(my_poly));
 tmp_node = tmp_node->next;
 tmp_node->next = NULL;
 }
 }


 while(poly1 || poly2) {
 tmp_node->next = (my_poly *) malloc(sizeof(my_poly));
 tmp_node = tmp_node->next;
 tmp_node->next = NULL;

 if(poly1) {
 tmp_node->exp = poly1->exp;
 tmp_node->coef = poly1->coef;
 poly1 = poly1->next;
 }
 if(poly2) {
 tmp_node->exp = poly2->exp;
 tmp_node->coef = poly2->coef;
 poly2 = poly2->next;
 }
 }
 printf("\n\n\t* Addition Complete *");
 }

OUTPUT:


Post a Comment

0 Comments