Add two polynomials using LINKED LIST in C
#include <stdio.h>
#include <stdlib.h>

typedef struct ll
{
    int c;
    int p;
    struct ll* next; 
} li ;


li *addend(int c, int p, li* head)
{
    li* temp,*cur;
    temp = malloc(sizeof(li));
    temp->c=c;
    temp->p=p;
    temp->next=NULL;
    cur = head;
    if(cur == NULL)
    {
        head = temp;
        return head;
    }
    while (cur->next!=NULL)
    {
        cur = cur->next;
    }
    cur->next=temp;
    return head;
}


void printlist(li* head)
{
    while(head!=NULL)
    {
        printf("%dx^%d + ",head->c,head->p);
        head = head->next;
    }
    printf("0\n");
}


li* input(int no, li* p)
{
    int co,po,loop = 1;
    printf("\nEnter Polynomial %d\n",no);
    while(loop == 1)
    {
        printf("Enter coeff ");
        scanf("%d",&co);
        printf("Enter power ");
        scanf("%d",&po); 
        printf("\nTo end this polynomial, enter 0 else 1 --> ");       
        scanf("%d",&loop);
        p = addend(co,po,p);
    }
    printf("polynomial %d = ",no);
    printlist(p);
    return p;
}


li* addpoly(li* h1, li* h2)
{
    li* t1, *t2;
    t1 = h1;
    t2 = h2;
    while(h1 != NULL && h2 != NULL)
    {
        while(h1->p != h2->p && h2 != NULL)
        {
            h2 = h2->next;
        }
        if(h1->p == h2->p)
        {
            h1->c += h2->c;
        }
        h2 = t2;
        h1 = h1->next;
    }
    return t1;
}



int main()
{

    li* p1=NULL;
    li* p2=NULL;
    p1 = input(1,p1);
    p2 = input(2,p2);

    p1 = addpoly(p1,p2);
    printlist(p1);
    return 0;
}
Comments (0)