Hello to anyone reading this. My problem with this program is that I seem to not be understanding how to add 2 polynomials which are entered sequentially into a linked list. I can add new polynomials or read the ones that are currently entered, but the adding and subtracting has given me issues. Here is what I currently have:
#include <iostream>
#include <cmath>
#include <cstddef>
using namespace std;
typedef float polyType;
struct polyInfo
{
int number;
int power;
polyInfo* link;
};
//typedef polyInfo* polyPtr;
//polyPtr head;
//polyPtr currPtr;
//polyPtr newNodePtr;
class Polynomial
{
private:
polyInfo *head;
int maxpow = 0;
public:
Polynomial(){}
void createPoly(int n, int p)
{
polyInfo *temp = new polyInfo();
temp->power = p;
temp->number = n;
temp->link = head;
head = temp;
if (maxpow < p)
{
maxpow = p;
}
}
void getPoly()
{
polyInfo *temp = head;
while (temp != NULL)
{
if (temp->number != 0)
{
cout << temp->number << "x^" << temp->power << " ";
}
temp = temp->link;
}
cout << "\n";
}
void addPoly()
{
polyInfo *temp = head;
while (temp != NULL)
{
if (temp->number != 0)
{
polyInfo *temp2 = head;
temp2 = temp2->link;
if (temp2->link != NULL)
{
if (temp->power == temp2->power)
{
temp->number = (temp->number)+(temp2->number);
temp2->number = 0;
temp = temp->link;
}
}
else
{
temp = NULL;
}
}
}
}
void subtractPoly()
{}
};
int main()
{
int menuNum;//used to see which menu option user chooses
int mainPower;
int mainNumber;
Polynomial mainPoly;
bool menu = true;
while (menu)
{
cout << "Enter 1 to create new polynomial"
<< "\nEnter 2 to read a polynomial"
<< "\nEnter 3 to add polynomials"
<< "\nEnter 4 to subtract polynomials"
<< "\nEnter 5 to end program :";
cin >> menuNum;
switch(menuNum)
{
case 1:
cout << "\nEnter the coefficient: ";
cin >> mainNumber;
cout << "\nEnter the exponent of X: ";
cin >> mainPower;
mainPoly.createPoly(mainNumber,mainPower);
break;
case 2:
mainPoly.getPoly();
break;
case 3:
mainPoly.addPoly();
break;
case 4:
mainPoly.subtractPoly();
break;
case 5:
cout << "End of program\n";
menu = false;
default:
cout << "\nInvalid Input, please try again\n\n";
break;
}
}
return 0;
}
I apologize for having almost no comments in the code. I usually go back through and add them in afterwards. I run a menu in main
that allows you to enter in a new polynomial, read them out, add them, or subtract them. I have the methods for inputting a new one and reading them out to the user. I have gotten this far on the code for my addition and it does not work. The problem cannot be fixed with two separate lists though, which is the majority of what I've found online. It has to be done through the one list which contains a number and power in each node.