双向循环列表中的赋值运算符以错误的顺序添加元素
assignment operator in double directed circular list adding elements in wrong order
我的双向循环列表中的赋值运算符有问题。当我有一个包含内容的列表并为其分配另一个包含内容的列表时,数字会混乱。我使用的输入是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;
相关文章:
- 以相反的顺序打印数组 - 为什么这在C++中是错误的?
- 为什么切换 if else 语句的顺序会导致错误?
- 为什么更改包含 psapi.h 的顺序会产生编译错误?(标识符 BOOL 未定义)
- 如果在 C++ 构造函数中以错误的顺序初始化对象数据,会发生什么类型的错误
- 由于选项卡顺序的原因,鼠标光标总是得到错误的hwnd-MFC应用程序
- 试图添加两个矢量,但添加顺序错误
- 尝试在 c++ 中按字母顺序排列单词时出现分段错误
- 生成文件似乎以错误的顺序编译文件
- 如何修复关卡顺序遍历问题(二叉树)的无限循环错误
- 为什么更改链接顺序可以修复一个系统上的一些链接错误?
- 分割错误取决于我在C 中声明的顺序
- Python是否以错误的顺序删除了swip?可以修改吗?
- 请在此程序中建议关卡顺序树遍历的错误
- 当某些错误可以接受时,顺序加载存储原子的内存顺序应该是什么
- 用错误的标志顺序编译后,是否删除*.cpp文件
- glDrawArrays的意外行为-参数顺序错误会产生所需的图像
- cout 和 cerr 的控制台输出顺序错误
- 按字母顺序排序名称,数组错误
- DUP2,EXECV,PIPES,分叉和代码以错误的顺序运行
- 二叉树顺序遍历错误:没有用于调用的匹配函数