I've made a polynomial class using an array-based linked list, but my addition function isn't working. It seems to work if the 2nd polynomial only has one term, but not if it has more than one. I'm not sure if it is a problem with my add function or my insertTerm function.
The class uses a ListNode array.
1 2 3 4 5 6 7 8 9 10 11 12
struct ListNode
{
/** A data item on the list. */
Polynomial_coefficient_type coefficient;
Polynomial_exponent_type exponent;
int next;
}; // end ListNode
ListNode array[50];
int head; // first used index
int free;
free is the first unused index in the array.
The last used index in the list has a next item of '-1'.
This is a case in my switch statement in my main function, which creates the second polynomial and then adds it to the original one:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
case 6:
cout << "\nEnter a term to create second polynomial.";
do
{
cout << "\nEnter the new term's coefficient: ";
cin >> a;
cout << "Enter the new term's exponent: ";
cin >> b;
p2.insertTerm(a, b);
cout << "Enter another term? (y/n): ";
cin >> cont;
} while (cont == 'y');
p1.add(p2);
break;
My add function inserts terms from the second polynomial into the original polynomial. The polynomial is then simplified, which isn't shown:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void Polynomial::add(Polynomial b)
{
//if b is empty, original polynomial is itself
if (!b.isEmpty())
{
int bTemp = b.head;
while (bTemp != -1) // '-1' is the 'next' item in the listnode of the last item in the list
{
insertTerm(b.array[bTemp].coefficient,
b.array[bTemp].exponent);
bTemp = b.array[bTemp].next;
}
}
}
I've already created a working pointer-based polynomial linked list, now I'm working on this one. And there is a doubling function which copies the array to a new array that is double the size of the original array, if it gets full.