我一直在为双向链表实现复制构造函数时遇到问题。我的教授为 DLL 类提供了框架,我正在将这些功能作为项目的一部分来实现。我在网上看到的所有内容都没有被证明有太大帮助,因为我看到的所有内容看起来都与我应该使用的代码格式完全不同。
对于初学者来说,这里是 DLL.h 文件
#include <string>
using namespace std;
struct Node{
string ssn;
string name;
Node* succ;
Node* pred;
};
class DLL{
private:
Node* headPtr;
int itemCount;
public:
DLL();
DLL(DLL& n); //Copy constructor
virtual ~DLL();
Node* getHeadPtr();
int search(string ss) const;
bool insert(string ss, string name, int & count);
bool remove(string ss, int & count);
int size();
void display();
};
除了析构函数,我还实现了所有其他函数,我还没有处理过,但到目前为止,这是我的复制构造函数代码:
DLL::DLL(DLL& n){
n.headPtr = nullptr;
n.itemCount = 0;
Node* temp = headPtr;
while(temp!= NULL){
temp = temp->succ;
insert(temp->ssn, temp->name, n.itemCount);
}
}
当我运行它时,我不断收到段错误。我在 Internet 上搜索了一段时间,但没有找到与此格式相似到足以让我理解的内容。
所有帮助/建议/建议将不胜感激,谢谢!
编辑:所以现在我有了这个,它在技术上是可行的,但要求是内存地址不同。我获得了一个文件 test.cpp,它使用示例参数运行函数,最后运行就像 Orig 列表:12、13、14(带有内存地址)后跟新复制的一个。
在我收到段错误 11 但现在它运行但位于相同的内存地址之前。
DLL::DLL(DLL& n){
Node* temp = n.headPtr;
headPtr = temp;
int count = 0;
while(temp != NULL){
insert(temp->ssn, temp->name, count);
temp = temp->succ;
}
最佳答案
您在复制构造函数中做的第一件事就是破坏原始列表。 n
是您正在从 复制的列表,通常不应修改,这就是为什么复制构造函数通常将 const Type&
作为输入参数。
你必须做类似的事情
DLL::DLL(DLL& n) {
int i = 0
Node* temp = n.headPtr;
while(temp != NULL){
temp = temp->succ;
insert(temp->ssn, temp->name, i++);
}
}
关于c++ - 双向链表的复制构造函数(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36051225/