оператор присваивания в двунаправленном круговом списке с добавлением элементов в неправильном порядке

У меня проблема с моим оператором присваивания в моем двустороннем круговом списке.
когда у меня есть список с контентом, и я назначаю другой список с контентом, числа перемешиваются. Ввод я использую 5 20 10 но когда я печатаю свой список, вывод 5 10 20, Мой код выглядит так:

#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

Я попытался использовать двух ходунков, изменил направление ходунков, сначала переместил ходок и добавил данные, переместил одного ходунка назад, а другой вперед и т. Д.

1

Решение

Ваш код назначения добавляет элементы obj в this в обратном порядке, потому что он шагает через previous указатели вместо next, + Изменить

walker = walker->previous;

в

walker = walker->next;
1

Другие решения


По вопросам рекламы ammmcru@yandex.ru
Adblock
detector