Untitled
unknown
plain_text
24 days ago
3.5 kB
2
Indexable
#include <stdio.h> #include <stdlib.h> // Define the structure for a term in the polynomial struct Term { int coeff; // Coefficient int x; // Exponent of x int y; // Exponent of y struct Term* next; // Pointer to the next term }; // Function to create a new term struct Term* createTerm(int coeff, int x, int y) { struct Term* newTerm = (struct Term*)malloc(sizeof(struct Term)); newTerm->coeff = coeff; newTerm->x = x; newTerm->y = y; newTerm->next = NULL; return newTerm; } // Function to read a polynomial struct Term* readPolynomial() { struct Term* head = NULL; struct Term* tail = NULL; int coeff, x, y; printf("Enter terms of the polynomial (coeff x y) and -1 to end:\n"); while (1) { scanf("%d", &coeff); if (coeff == -1) break; // End input scanf("%d %d", &x, &y); struct Term* newTerm = createTerm(coeff, x, y); if (head == NULL) { head = tail = newTerm; // First term } else { tail->next = newTerm; // Link new term tail = newTerm; // Update tail } } return head; } // Function to add two polynomials struct Term* addPolynomials(struct Term* poly1, struct Term* poly2) { struct Term* result = NULL; struct Term* tail = NULL; while (poly1 != NULL || poly2 != NULL) { int coeff = 0; int x, y; if (poly1 != NULL && (poly2 == NULL || poly1->x > poly2->x || (poly1->x == poly2->x && poly1->y > poly2->y))) { coeff = poly1->coeff; x = poly1->x; y = poly1->y; poly1 = poly1->next; } else if (poly2 != NULL && (poly1 == NULL || poly2->x > poly1->x || (poly2->x == poly1->x && poly2->y > poly1->y))) { coeff = poly2->coeff; x = poly2->x; y = poly2->y; poly2 = poly2->next; } else { coeff = poly1->coeff + poly2->coeff; x = poly1->x; y = poly1->y; poly1 = poly1->next; poly2 = poly2->next; } // Only add non-zero coefficients to the result if (coeff != 0) { struct Term* newTerm = createTerm(coeff, x, y); if (result == NULL) { result = tail = newTerm; // First term } else { tail->next = newTerm; // Link new term tail = newTerm; // Update tail } } } return result; } // Function to print a polynomial void printPolynomial(struct Term* poly) { if (poly == NULL) { printf("0\n"); return; } while (poly != NULL) { printf("%dx^%dy^%d", poly->coeff, poly->x, poly->y); poly = poly->next; if (poly != NULL) { printf(" + "); } } printf("\n"); } // Main function to demonstrate polynomial addition int main() { printf("Polynomial 1:\n"); struct Term* poly1 = readPolynomial(); printf("Polynomial 2:\n"); struct Term* poly2 = readPolynomial(); struct Term* result = addPolynomials(poly1, poly2); printf("Resultant Polynomial:\n"); printPolynomial(result); // Free memory (not shown for brevity) // You should implement a function to free the linked list memory return 0; }
Editor is loading...
Leave a Comment