DSA ADD Polynomial using Singly
Fri Aug 25 2023 06:24:23 GMT+0000 (Coordinated Universal Time)
Saved by @Astik
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
struct node {
int coefficient;
int exponent;
struct node* next;
};
struct node* create_node(int coef, int exp) {
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->coefficient = coef;
new_node->exponent = exp;
new_node->next = NULL;
return new_node;
}
void insert_term(struct node** poly, int coef, int exp) {
if (*poly == NULL) {
*poly = create_node(coef, exp);
} else {
struct node* temp = *poly;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = create_node(coef, exp);
}
}
struct node* add_polynomials(struct node* poly1, struct node* poly2) {
struct node* result = NULL;
while (poly1 != NULL && poly2 != NULL) {
if (poly1->exponent > poly2->exponent) {
insert_term(&result, poly1->coefficient, poly1->exponent);
poly1 = poly1->next;
} else if (poly1->exponent < poly2->exponent) {
insert_term(&result, poly2->coefficient, poly2->exponent);
poly2 = poly2->next;
} else {
int sum = poly1->coefficient + poly2->coefficient;
if (sum != 0) {
insert_term(&result, sum, poly1->exponent);
}
poly1 = poly1->next;
poly2 = poly2->next;
}
}
while (poly1 != NULL) {
insert_term(&result, poly1->coefficient, poly1->exponent);
poly1 = poly1->next;
}
while (poly2 != NULL) {
insert_term(&result, poly2->coefficient, poly2->exponent);
poly2 = poly2->next;
}
return result;
}
void display_polynomial(struct node* poly) {
while (poly != NULL) {
printf("%dx^%d", poly->coefficient, poly->exponent);
poly = poly->next;
if (poly != NULL) {
printf(" + ");
}
}
printf("\n");
}
int main() {
int expo, data, count;
int i;
struct node* poly1 = NULL;
struct node* poly2 = NULL;
struct node* result;
// Insert terms into polynomial 1
printf("\nEnter number of terms in poly 1: ");
scanf("%d", &count);
for(i=0;i<count;i++){
printf("\nEnter element %d", i+1);
printf("\nEnter coefficient: ");
scanf("%d",&data);
printf("\nEnter exponent: ");
scanf("%d", &expo);
insert_term(&poly1, data, expo);
}
//insert_term(&poly1, 5, 4);
//insert_term(&poly1, 2, 3);
//insert_term(&poly1, -2, 2);
//insert_term(&poly1, 17, 0);
// Insert terms into polynomial 2
printf("\nEnter number of terms in poly 2: ");
scanf("%d", &count);
for(i=0;i<count;i++){
printf("Enter element %d\n", i+1);
printf("\nEnter coefficient: ");
scanf("%d",&data);
printf("\nEnter exponent: ");
scanf("%d", &expo);
insert_term(&poly2, data, expo);
}
//insert_term(&poly2, 15, 3);
//insert_term(&poly2, 6, 2);
//insert_term(&poly2, -2, 0);
printf("Polynomial 1: ");
display_polynomial(poly1);
printf("Polynomial 2: ");
display_polynomial(poly2);
result = add_polynomials(poly1, poly2);
printf("Result: ");
display_polynomial(result);
getch();
return 0;
}



Comments