Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Program to add two polynomials using singly linked list.
- #include<stdio.h>
- #include<conio.h>
- #include<stdlib.h>
- struct node
- {
- int coeff,exp;
- struct node *link;
- };
- void display(struct node *t)
- {
- printf("\n The resultant polynomial is : ");
- while(t->link!=NULL)
- {
- printf("%dx^%d+",t->coeff,t->exp);
- t=t->link;
- }
- printf("%dx^%d",t->coeff,t->exp);
- }
- void add(struct node *p,struct node *q)
- {
- struct node *temp,*s;
- s=NULL;
- while(p!=NULL && q!=NULL)
- {
- struct node *r=(struct node*)malloc(sizeof(struct node));
- if(p->exp==q->exp)
- {
- r->coeff=p->coeff+q->coeff;
- r->exp=p->exp;
- r->link=NULL;
- p=p->link;
- q=q->link;
- }
- else if(p->exp>q->exp)
- {
- r->exp=p->exp;
- r->coeff=p->coeff;
- r->link=NULL;
- p=p->link;
- }
- else if(p->exp<q->exp)
- {
- r->exp=q->exp;
- r->coeff=q->coeff;
- r->link=NULL;
- q=q->link;
- }
- if(s==NULL)
- s=r;
- else
- {
- temp=s;
- while(temp->link!=NULL)
- temp=temp->link;
- temp->link=r;
- }
- }
- if(p==NULL && q==NULL)
- {
- goto x;
- }
- else if(p!=NULL)
- {
- temp=s;
- while(temp->link!=NULL)
- temp=temp->link;
- temp->link=p;
- }
- else if(q!=NULL)
- {
- temp=s;
- while(temp->link!=NULL)
- temp=temp->link;
- temp->link=q;
- }
- x:
- display(s);
- }
- void main()
- {
- int c,e,ch;
- struct node *p,*last,*q,*temp1;
- clrscr();
- //Creation of first linked list.
- p=NULL; last=NULL;
- printf("\n For first linked list.");
- do
- {
- printf("\n Enter coeff and exp : ");
- scanf("%d %d",&c,&e);
- temp1=(struct node*)malloc(sizeof(struct node));
- temp1->coeff=c;
- temp1->exp=e;
- temp1->link=NULL;
- if(last==NULL)
- {
- p=temp1;
- last=p;
- }
- else
- {
- last->link=temp1;
- last=temp1;
- }
- printf("\n Do u want to add some more nodes (1 or 0): ");
- scanf("%d",&ch);
- }while(ch==1);
- //Creation of second linked list.
- q=NULL; last=NULL;
- printf("\n For second linked list.");
- do
- {
- printf("\n Enter coeff and exp : ");
- scanf("%d %d",&c,&e);
- temp1=(struct node*)malloc(sizeof(struct node));
- temp1->coeff=c;
- temp1->exp=e;
- temp1->link=NULL;
- if(last==NULL)
- {
- q=temp1;
- last=q;
- }
- else
- {
- last->link=temp1;
- last=temp1;
- }
- printf("\n Do u want to add some more nodes (1 or 0): ");
- scanf("%d",&ch);
- }while(ch==1);
- add(p,q);
- getch();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement