3.1 Polynomial Addition Using Linked List
Fri Aug 25 2023 06:24:16 GMT+0000 (Coordinated Universal Time)
Saved by @109_Vivek
#include <stdio.h> #include <conio.h> #include <stdlib.h> struct Node { int coff; int pow; struct Node *next; }; struct Node *head1 = NULL; struct Node *head2 = NULL; struct Node *createNode(int i) { struct Node *newNode = (struct Node *)malloc(sizeof(struct Node)); printf("Enter Coefficient of x^%d : ", i); scanf("%d", &newNode->coff); newNode->pow = i; newNode->next = NULL; return newNode; } struct Node *create(int i, int coff) { struct Node *newNode = (struct Node *)malloc(sizeof(struct Node)); newNode->coff=coff; newNode->pow = i; newNode->next = NULL; return newNode; } void displayPolynomial(struct Node *head) { struct Node *temp = head; while (temp != NULL) { printf("%dx^%d ", temp->coff, temp->pow); temp = temp->next; } printf("\n"); } struct Node *createPolynomial(struct Node *head, int n) { int i; for (i = 0; i <= n; i++) { if (head == NULL) { head = createNode(i); } else { struct Node *temp = head; while (temp->next != NULL) { temp = temp->next; } temp->next = createNode(i); } } return head; } void addPolynomials(struct Node *temp1, struct Node *temp2) { struct Node *finalHead = NULL; int i = 0; while (temp1 != NULL && temp2 != NULL) { if (finalHead == NULL) { finalHead = create(i,temp1->coff+temp2->coff); } else { struct Node *temp = finalHead; while (temp->next != NULL) { temp = temp->next; } temp->next = create(i,temp1->coff+temp2->coff); } i++; temp1=temp1->next; temp2=temp2->next; } if(temp1!=NULL){ struct Node* temp=finalHead; while(temp->next!=NULL) { temp=temp->next; } temp->next=temp1; } else if(temp2!=NULL){ struct Node* temp=finalHead; while(temp->next!=NULL) { temp=temp->next; } temp->next=temp2; } printf("\nAdded Polynomial : "); displayPolynomial(finalHead); } void main() { // Create First Polynomial int a, b; clrscr(); printf("Enter Highest Exponent in Polynomial P : "); scanf("%d", &a); head1 = createPolynomial(head1, a); // Create Second Polynomial printf("Enter Highest Exponent in Polynomial Q : "); scanf("%d", &b); head2 = createPolynomial(head2, b); printf("\nPolynomial P : "); displayPolynomial(head1); printf("\nPolynomail Q : "); displayPolynomial(head2); addPolynomials(head1, head2); getch(); }
Comments