Reputation: 31
Below is my source code which is to generate 2 polynomials which are given by the user input. Now, I'm stuck on how to add both polynomials and display the result. I have the idea how to evaluate which is we check the exponent in the list. If same, the coefficient will add. If not, the current node will proceed to the next node and compare to the other node.Is that right? Actually I'm quite confused about linked list.
#include<iostream>
using namespace std;
class Node{
public :
int coef;
int exp;
Node *next;
private:
};
class List{
public:
List(){
head = NULL;
}
void insert(int x, int y){ //inserting node
Node *newNode = new Node;
newNode->coef = x;
newNode->exp = y;
newNode->next = NULL;
if(head==NULL){
head = newNode;
}
else{
Node *currNode = head;
while(currNode->next!=0){
currNode = currNode->next;
}
currNode->next = newNode;
}
}
void display(){ //display the expression
Node *currNode = head;
cout<<"\n\n\t";
while(currNode->next!=0){
//cout<<"Coef: "<<currNode->coef<<"\t"<<"Expo: "<<currNode->exp<<endl;
cout<<currNode->coef<<"X^"<<currNode->exp<< "+";
currNode = currNode->next;
}
cout<<currNode->coef<<"X^"<<currNode->exp<<endl;
//cout<<"Coef: "<<currNode->coef<<"\t"<<"Expo: "<<currNode->exp<<endl;
}
private:
Node *head;
};
int main(){
List seq1,seq2;
int x,y,a,b;
cout<<"Enter your expression 1: "<<endl;
while(cin>>x>>y,x!=0&&y!=-1){
seq1.insert(x,y);
}
seq1.display();
cout<<endl;
cout<<"Enter your expression 2: "<<endl;
while(cin>>a>>b,a!=0&&b!=-1){
seq2.insert(a,b);
}
seq2.display();
return 0;
}
Upvotes: 1
Views: 11127
Reputation: 803
As you guessed, you'll need to traverse each list and compare the exponent. If the exponents match, you add the coefficients. What you want to look at more carefully is the way you use your linked list. Currently, you are adding each new entry of the polynomial at the end regardless of the value of the exponent. Also, if the user enters the same exponent twice you add a second node.
If you keep the expressions in the linked list ordered by exponent, it will make it much easier to add polynomials together and much more efficient too.
Upvotes: 1