Sunday, 6 March 2022

2 - Polynomial Linked List

 2 Polynomial Linked List

#include<stdio.h>
#include<stdlib.h>

struct node  {
    int coeff;
    int exp;
    struct node* next;
}*head1 = 0, *head2 = 0, *ptr1 = 0, *ptr2 = 0, *head = 0, *fin = 0, *temp, *fin;

struct node* insert(struct node* head, int co, int ex) {
    struct node* new1 = malloc(sizeof(struct node));
    new1->coeff = co;
    new1->exp = ex;
    new1->next = 0;
    if(head == 0 || ex > head->exp) {
        new1->next = head;
        head = new1;
    } else {
        temp = head;
        while(temp->next != 0 && temp->next->exp >= ex) {
            temp = temp->next;
        }
        new1->next = temp->next;
        temp->next = new1;
    }
    return head;
}

struct node* create(struct node* temp) {
    int terms, co, ex;
    printf("\nEnter no of terms : \t");
    scanf("%d", &terms);
    for(int i=0; i<terms; i++) {
        printf("\nEnter coeff and exp for %d term : \t", i+1);
        scanf("%d %d", &co, &ex);
        temp = insert(temp, co, ex);
    }
    return temp;
}

struct node* polyadd(struct node* head1, struct node* head2) {
    ptr1 = head1, ptr2 = head2;
    while(ptr1 != 0 && ptr2 != 0) {
        if(ptr1->exp == ptr2->exp) {
            fin = insert(fin, ptr1->coeff + ptr2->coeff, ptr1->exp);
            ptr1 = ptr1->next;
            ptr2 = ptr2->next;
        }
        else if(ptr1->exp > ptr2->exp) {
            fin = insert(fin, ptr1->coeff, ptr1->exp);
            ptr1 = ptr1->next;
        } else {
            fin = insert(fin, ptr2->coeff, ptr2->exp);
            ptr2 = ptr2->next;
        }
    }
    return fin;
}

void display(struct node* head) {
    if(head == NULL) {
        printf("List Empty");
    } else {
        temp = head;
        while(temp!=0) {
            printf("%d x^%d", temp->coeff, temp->exp);
            temp = temp->next;
            if(temp != NULL) {
                printf(" + ");
            } else {
                printf("\n");
            }
        }
    }
}

int main() {
    printf("\nCreate 1st polynomial");
    head1 = create(head1);
    printf("\n******************************************************\n");
    display(head1);

    printf("\nCreate 2nd polynomial");
    head2 = create(head2);
    printf("\n******************************************************\n");
    display(head2);
   
    fin = polyadd(head1, head2);
    printf("\n******************************************************\n");
    display(fin);
}

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home