Write a function to add two polynomials. Do not destroy the input. Use a linked list implementation with a dummy head node. Note: The zero polynomial is represented by an empty list with only the dummy head node.
Format of functions:
Polynomial Add( Polynomial a, Polynomial b );
where Polynomial is defined as the following:
typedef struct Node *PtrToNode;
struct Node {
int Coefficient;
int Exponent;
PtrTonode Next;
};
typedef PtrTonode Polynomial;
The function Add is supposed to return a polynomial which is the sum of a and b.
Sample program of judge:#include#include typedef struct Node *PtrToNode; struct Node { int Coefficient; int Exponent; PtrTonode Next; }; typedef PtrTonode Polynomial; Polynomial Read(); void Print( Polynomial p ); Polynomial Add( Polynomial a, Polynomial b ); int main() { Polynomial a, b, s; a = Read(); b = Read(); s = Add(a, b); Print(s); return 0; }
Sample Input:
4 3 4 -5 2 6 1 -2 0 3 5 20 -7 4 3 1
Sample Output:
5 20 -4 4 -5 2 9 1 -2 0
Polynomial Add( Polynomial a, Polynomial b )
{
Polynomial s = a;// make s point to any dummy head
Polynomial pa = a->Next, pb = b->Next;
Polynomial cur = s;// as the cursor, in order to make s unchanged
while (pa != NULL && pb != NULL) {// When any polynomial traversal is completed, we can stop
// compare the exponents of each term of a and b
if (pa->Exponent > pb->Exponent) {
cur->Next = pa;
pa = pa->Next;
cur = cur->Next;
}
else if (pa->Exponent < pb->Exponent) {
cur->Next = pb;
pb = pb->Next;
cur = cur->Next;
}
else {// if the exponent of pa equals to the exponent of pb
pb->Coefficient += pa->Coefficient;// here I select the b as the base
if (pb->Coefficient != 0) {
cur->Next = pb;
cur = cur->Next;
}
pa = pa->Next;
pb = pb->Next;
}
}
if (pa == NULL) {// If the pa has been traversed, let's point cur to psb
cur->Next = pb;
}
else {// If the pb has been traversed, let's point cur to pa
cur->Next = pa;
}
return s;
}



