{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

HW1A - p.85 3.6 Write a function to add two polynomials Do...

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

View Full Document Right Arrow Icon
p.85 3.6 Write a function to add two polynomials. Do not destroy the input. Use a linked list implementation. If the polynomials have M and N terms, respectively, what is the time complexity of your program? typedef struct Node *PtrToNode; struct Node { int Coefficient; int Exponent; PtrToNode Next; }; typedef PtrToNode Polynomial; /* Nodes are sorted in decreasing order of exponents.*/ Polynomial Add ( Polynomial a, Polynomial b ) { /* return a polynomial which is the sum of a and b*/ /*use linked list with a head node */ PtrToNode front, tail; int sum; /* create a head node */ tail = malloc( sizeof (Node)); if ( tail ==Null) FatalError( "The memory is full"); front = tail; front->Exponent=-1; a=a->Next; b=b->Next; while ( a && b ) switch ( COMPARE(a-> Exponent, b-> Exponent) ) { case -1: Attach(b-> Coefficient, b-> Exponent, &tail); b = b-> Next; break ; case 0: sum = a-> Coefficient + b-> Coefficient; if ( sum ) Attach(sum, a-> Exponent, &tail); a = a-> Next; b = b-> Next; break ; case 1: Attach(a-> Coefficient, a-> Exponent, &tail); a = a-> Next; break ; } /* copy rest of list a and then list b */
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
for ( ; a; a = a-> Next ) Attach(a-> Coefficient, a-> Exponent, &tail);
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 ]}