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?