{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

polynomial - #include #include #include...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Sheet1 Page 1 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h>/*math.h required for pow() function used in EVALUTE polynomial*/ /*pow(a,b) gives a raised to power b*/ struct node {/*Defines struct node for each node of a Linked List*/ int exponent double coefficient struct node *next } typedef struct node ListNode ListNode *addNode(ListNode *first,int exp,double coeff)/*Adds a new node at end of Linked List with first as pointer to first nod {/*Puts given fields exp and coeff in new node*/ ListNode *temp, *newNode newNode = (ListNode *)malloc(sizeof(ListNode)) newNode->exponent = exp newNode->coefficient = coeff newNode->next = NULL if(first==NULL) return newNode temp = first while(temp->next != NULL) temp = temp->next temp->next = newNode return first } ListNode *CreateList(char *str)/*Creates Linked List containing the polynomial given in the file*/ {/*Returns pointer to the first node of this Linked List*/ int exp, sign double coeff ListNode *poly=NULL char *t, c t = strtok(str," ") if(strcmp(t,"-")==0) { sign = -1 t = strtok(NULL," ") } else sign = 1 do { if(sscanf(t,"%lfx^%d",&coeff,&exp)==2)/* if term looks like 2.5x^4*/ i else if(sscanf(t,"x^%d",&exp)==1)/* if term looks like x^4*/ coeff = 1.0
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Sheet1 Page 2 else if((sscanf(t,"%lf%c",&coeff,&c)==2)&&(c=='x'))/* if term looks like 2.5x*/ exp = 1 else if((sscanf(t,"%c",&c)==1)&&(c=='x'))/* if term looks like x*/ { exp = 1 coeff = 1.0 } else if(sscanf(t,"%lf",&coeff)==1)/* if term looks like 2.5*/ exp = 0 else printf("ERROR!\n") coeff = coeff*sign poly = addNode(poly,exp,coeff) if((t=strtok(NULL," "))==NULL)/* get next operator*/ break if(strcmp(t,"+")==0)/* sign: 1 for positive, -1 for negative*/ sign = 1 else if(strcmp(t,"-")==0) sign = -1 else printf("ERROR!\n") } while((t = strtok(NULL," "))!=NULL) return poly } ListNode *freePoly(ListNode *poly)/*frees the memory of Linked List list*/ { ListNode *i=poly, *temp while(i!=NULL) { temp = i i = i->next free(temp) } return NULL } ListNode *addPoly(ListNode *poly1, ListNode *poly2)/*Adds two polynomials given in Linked Lists poly1 and poly2*/ {/*Returns Linked List that contains the Sum*/ ListNode *i=poly1,*j=poly2, *sum = NULL double coeff while((i!=NULL)&&(j!=NULL)) { if(i->exponent > j->exponent) { sum = addNode(sum,i->exponent,i->coefficient) i = i->next }
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}