Discuss the representation of polynomial of single variable using linked list. Write a C functions to add two such polynomials represented by linked list.
Representing a polynomial of a single variable using a linked list involves creating a node structure to the coefficient and exponent of each term in the polynomial. The C function to add two such polynomials represented by linked lists compares the coefficients and exponents corresponding nodes in the linked lists and performs the necessary operations to add the polynomials. Here's a possible implementation of this concept in C:
#include <stdio.h> #include <stdlib.h> struct Node { int coeff; int exp; struct Node* next; }; typedef struct Node Node; Node* createNode(int coeff, int exp) { Node* newNode = (Node*)malloc(sizeof(Node)); if (newNode ==) { printf("Memory allocation failed"); exit(); } newNode->coeff = coeff; newNode->exp = exp; newNode->next NULL; return newNode; } void insertNode(Node** poly, int coeff, int exp) { Node* temp = *poly; Node* newNode = createNode(coeff, exp); if (*poly == NULL { *poly = newNode; } else { while (temp->next != NULL) { temp = temp->next; } temp->next = newNode; } } Node*Polynomials(Node* poly1, Node* poly2) { Node* result = NULL; while (poly1 != NULL || poly2 != NULL) { (poly1 == NULL) { insertNode(&result, poly2->coeff poly2->exp); 2 = poly2->next; } else if (2 == NULL) { insertNode(&result, poly1->, poly1->exp); poly1 = poly1->next; } else { if (poly1->exp > poly2->exp { insertNode(&result, poly1->coeff, poly1->exp); poly1 = poly1->next; } else if (poly1->exp < poly2->exp) { insertNode(&result, poly2->coeff, poly2->exp); poly2 = poly2->next; } else { Node(&result, poly1->coeff + poly2->coeff, poly1->); poly1 = poly1->next; poly2 = poly2->next; } } return result; } void display(Node* poly) { whilepoly != NULL) { printf("%dx^%d ", poly->coeff, poly->exp); (poly->next != NULL) { printf("+ "); } poly = poly->next; } printf("\n"); } int main() { Node* poly1 = NULL; Node* poly2 =; insertNode(&poly1, 5, 2); insertNodepoly1, 4, 1); insertNode(&poly1, 2, 0); insertNode(&poly2, 3, 3); insertNode(&poly2, 2, 1); insertNode(&poly, 1, 0); printf("First polynomial: "); display(poly1); printf("Second polynomial: "); display(poly2); Node* result = addPolynomials(poly1,2); printf("Sum of the polynomials: "); display(result); return 0; }
In implementation, the Node
structure represents each term in the. The createNode
function creates a new node with the given coefficient and exponent. The insertNode
function inserts a new node the end of the linked list. The addPolynomials
function adds two polynomials represented by linked lists and returns the result as a linked list. The display
function is to display the polynomial in a readable format. The main
function demonstrates the usage of these functions by creating two polynomials, adding them, and displaying the result.