gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:44:26 26 4
gpt4 key购买 nike

我的双向循环列表中的赋值运算符有问题。当我有一个包含内容的列表并将另一个包含内容的列表分配给它时,数字会困惑。我使用的输入是 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 指针而不是 >下一步。改变

walker = walker->previous;

walker = walker->next;

关于c++ - 双向循环列表中的赋值运算符以错误的顺序添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29863450/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com