A linked list is a bad way to store a polynomial:
- adding to the tail is expensive unless you keep a tail pointer.
- There's nothing to prevent the user from entering the terms out of order.
- You have to store the exponent of each term.
I would store it as a vector where vec[n] is the coefficient of x
n
- Impossible to get items out of order.
- Random access to coefficients
- Guarantee that if x
n exists, then all the previous terms exist too.
If you must use a linked list, then take Salem C's advice. In addition, I'd suggest:
- appendNode() needs to initialize temp
- Addpoly() should not print the result. That's showpoly's job. Just call showpoly() in main after calling addpoly()
- Modify addpoly() to handle the case where the polynomials are not of the same order: i.e., when p1's max exponent is 3 and p2's max exponent is 5.
- Modify addpoly() to handle the case where polynomials have missing terms (which presumably means the coefficient is zero).
Ideally, you'd also change appendNode() to insert the new node in the right position, so the user can enter the nodes in any order.
Also, consider using for loops to go through the list. For example:
1 2 3 4 5 6
|
void showdata(Poly *head)
{
for (Poly *temp = head; temp; temp = temp->next) {
cout << temp->coff << "x^" << temp->expo<< " + ";
}
}
|