{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

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

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

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 */

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

View Full Document
for ( ; a; a = a-> Next ) Attach(a-> Coefficient, a-> Exponent, &tail);
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}