I am implementing a class Polynomial with private members consisting of a singly linked list for its coefficient and an int representing the highest degree. The constructor takes in a vector which represents the coefficients in the polynomial. This is my implementation of the constructor and the output operator.
#include <iostream>
#include <vector>
using namespace std;
struct Node{
Node(int data = 0, Node* next = nullptr) : data(data), next(next) {}
int data;
Node* next;
};
class Polynomial{
friend ostream& operator<<(ostream& os, const Polynomial& p);
public:
Polynomial(vector<int> poly){
Node* temp = co;
for(int i : poly){
temp = new Node(i);
temp = temp->next;
}
degree = poly.size() - 1;
}
private:
Node* co;
int degree;
};
ostream& operator<<(ostream& os, const Polynomial& p){
Node* temp = p.co;
int degree = p.degree;
while(temp != nullptr){
if(degree == 1){
os << temp->data << "x" << " ";
}else if(degree == 0){
os << temp->data;
}else{
os << temp->data << "x^" << degree << " ";
}
degree--;
temp = temp->next;
}
return os;
}
When I try to test my code the output was 686588744, which I assume refers to a place in memory, rather than the expected outcome of 17.
int main(){
Polynomial p1({17});
cout << p1;
}
Could anyone point out where I made a mistake in my code?
CodePudding user response:
This constructor
Polynomial(vector<int> poly){
Node* temp = co;
for(int i : poly){
temp = new Node(i);
temp = temp->next;
}
degree = poly.size() - 1;
}
is invalid. Actually it does not build a list. Instead it produces numerous memory leaks.
For example at first a node was allocated and its address was assigned to the pointer temp
and then the pointer was reassigned with the value stored in the data member temp->next
that is a null pointer. So the address of the allocated node was lost.
And moreover the pointer co
is leaved uninitialized.
You can rewrite it for example the following way
Polynomial( const vector<int> &poly) : co( nullptr ), degree( 0 )
{
Node **current = &co;
for( int i : poly )
{
*current = new Node(i);
current = &( *current )->next;
}
if ( not poly.empty() ) degree = poly.size() - 1;
}