I am trying to add polynomials of different lengths together, but my algorithm keeps being inconsistent. Occasionally, it will output a wrong number and other times it won't.
I've traced the code multiple times and am unsure of the issue here. Any thoughts are appreciated.
This is the overloaded operator that I need to implement. I am essentially trying to increment until both Polynomials are the same length, then add them. It is part of a larger Polynomial class.
Polynomial& operator+=(const Polynomial& rhs) {
Node* this_step = head->next;
Node* step = rhs.head->next;
size_t overflow = rhs.size - size;
while (overflow > 0) {
Node* this_prev = this_step->prev; // *this head node
// slide in the new node in the front of *this
Node* import = new Node{step->data, this_prev, this_step};
this_step->prev = import;
head = import; // reset head
// increment {internal} size to fit new node
size += 1;
// decrement amount of overflow
overflow -= 1;
// move to next available node
step = step->next;
}
while (step != nullptr && this_step != nullptr) {
this_step->data += step->data;
step = step->next;
this_step = this_step->next;
}
return *this;
}
Structure of Node:
struct Node {
int data;
Node* prev;
Node* next;
};
Polynomial Fields:
Node* head;
size_t size;
Use Case: I want to implement the + operator as well but as I noted earlier it is inconsistent.
Polynomial operator+(const Polynomial& lhs, const Polynomial& rhs) {
Polynomial res;
res += rhs;
res += lhs;
return res;
}
I expect to get 0 7, which would represent 0x + 7. But instead I get 5 7, which is incorrect.
Aucun commentaire:
Enregistrer un commentaire