Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<conio.h>
- // This is my implementation to add and multiply
- // two polynomials using linked list
- // So far, it just inputs and displays the polynomial
- struct term {
- int exp;
- int coef;
- struct term *next;
- };
- struct term * addTerm(struct term * polynomial,int exp,int coef){ // adds a term to polynomial
- if(polynomial == NULL ){
- polynomial = (struct term *) malloc(sizeof(struct term));
- polynomial->exp = exp;
- polynomial->coef = coef;
- polynomial->next = NULL;
- }else{
- struct term *newTerm = (struct term *)malloc(sizeof(struct term));
- newTerm->exp = exp;
- newTerm->coef = coef;
- newTerm->next = NULL;
- struct term *temp = polynomial;
- while(temp->next != NULL){
- temp = temp->next;
- }
- temp->next = newTerm;
- }
- return polynomial;
- }
- void display(struct term * polynomial){ // displays the polynomial
- struct term *p = polynomial;
- if(p != NULL){
- while(p != NULL){
- printf("+ %dx%d ",p->coef,p->exp);
- p = p->next;
- }
- }
- p = NULL;
- }
- struct term * addPolynomials(struct term * poly1, struct term * poly2){
- struct term * polynomial3 = (struct term *) malloc(sizeof(struct term)); // final answer
- struct term * poly1Copy = poly1; // keeping copies
- struct term * poly2Copy = poly2; // in case we need to restart passes
- while(poly1 != NULL && poly2 != NULL){
- if(poly1->exp == poly2->exp){
- polynomial3 = addTerm(polynomial3,poly1->exp,(poly1->coef + poly2 -> coef)); // add the term to final answer
- poly1 = poly1->next; // go to next term
- poly2 = poly2->next; // go to next term
- }
- if(poly1->exp > poly2->exp){
- poly1 = poly1->next;
- }
- if(poly2->exp > poly1->exp ){
- poly2 = poly2->next;
- }
- }
- return polynomial3;
- }
- void main(){ // run it
- int i = 0;
- int coef = 0;
- int exp = 0;
- struct term * polynomial1 = NULL;
- struct term * polynomial2 = NULL;
- printf("Entering polynomial 1: \n");
- while(i++ < 3){
- printf("Enter CoEfficient and Exponent for Term %d ",i);
- scanf("%d %d",&coef,&exp);
- polynomial1 = addTerm(polynomial1,exp,coef);
- }
- i = 0;
- display(polynomial1); // show it
- printf("\n\nEntering polynomial 2: \n");
- while(i++ < 4){
- printf("Enter CoEfficient and Exponent for Term %d ",i);
- scanf("%d %d",&coef,&exp);
- polynomial2 = addTerm(polynomial1,exp,coef);
- }
- display(polynomial2); // show it
- printf("\n\nDisplaying Addition \n");
- display(addPolynomials(polynomial1,polynomial2));
- getch();
- }
Advertisement
Add Comment
Please, Sign In to add comment