双向循环列表中的赋值运算符以错误的顺序添加元素

assignment operator in double directed circular list adding elements in wrong order

本文关键字:错误 顺序 添加 元素 赋值运算符 循环 列表      更新时间:2023-10-16

我的双向循环列表中的赋值运算符有问题。当我有一个包含内容的列表并为其分配另一个包含内容的列表时,数字会混乱。我使用的输入是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

我尝试使用两个

助行器,改变助行器的方向,先移动助行器,然后添加数据,向后移动一个助行器,向前移动另一个助行器,等等。

您的赋值代码以相反的顺序将obj元素添加到this,因为它是单步执行previous指针而不是next。改变

walker = walker->previous;

walker = walker->next;