Reputation: 35
I have problem with my assignment operator in my double directed circular list.
when I have a list with content and assign another list with content to it the numbers are jumbled up. The input I use is 5 20 10
but when I print my list the output is 5 10 20
. My code looks like this:
#ifndef CDDLIST_H
#define CDDLIST_H
template <typename T>
class CircularDoubleDirectedList<T>{
public:
static enum direction{ FORWARD, BACKWARD };
CircularDoubleDirectedList<T>& operator= (const CircularDoubleDirectedList<T>& obj);
void addAtCurrent(const T& data);
private:
class Node{
public:
T data;
Node *next;
Node *previous;
Node(const T& data){
this->data = data;
this->next = nullptr;
this->previous = nullptr;
};
Node(){
this->data = NULL;
this->next = nullptr;
this->previous = nullptr;
};
~Node(){};
};
Node *current;
direction currentDirection;
int numberOfElements;
};
template <typename T>
CircularDoubleDirectedList<T>& CircularDoubleDirectedList<T>::operator= (const CircularDoubleDirectedList<T>& obj){
if (this !=&obj){
this->currentDirection = obj.currentDirection;
this->current = nullptr;
this->numberOfElements = 0;
Node* walker = obj.current;
for (int i = 0; i < obj.numberOfElements; i++){
walker = walker->previous;
addAtCurrent(walker->data);
}
}
return *this;
}
template <typename T>
void CircularDoubleDirectedList<T>::addAtCurrent(const T& data){
if (this->numberOfElements == 0){
Node *node = new Node(data);
this->current = node;
node->next = node;
node->previous = node;
this->numberOfElements++;
}
else{
Node *node = new Node(data);
node->previous = this->current;
node->next = this->current->next;
this->current->next = node;
this->current = node;
this->current->next->previous=this->current;
this->numberOfElements++;
}
}
#endif
I have tried to use two walkers, changed direction of the walker(s), moved the walker(s) first and added data second, moved one walker backwards and the other forwards, etc.
Upvotes: 1
Views: 180
Reputation: 780929
Your assignment code is adding the elements of obj
to this
in reverse order, because it's stepping through the previous
pointers instead of next
. Change
walker = walker->previous;
to
walker = walker->next;
Upvotes: 1