问题描述:

I have been having trouble implementing a copy constructor for a doubly linked list. My professor provided a skeleton for a DLL class and i am implementing the functions as part of a project. Everything i have seen online has not proven to be too helpful because everything i see looks entirely different to the format of code i am supposed to be using.

For starters here's the DLL.h file

#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();

};

I have all the other functions implemented besides the destructor, which i haven't worked on yet but so far this is my code for the copy constructor:

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);

}

}

When i run this i keep getting segfault's. I have searched for some time on the internet but nothing similar enough to this format for me to comprehend has come up.

All help/suggestions/advice would be greatly appreciated thanks!

Edit: So now i have this, which works technically but a requirement is that the memory addresses are different. I was provided with a file test.cpp that runs the functions with example parameters and in the end the run is like Orig list: 12, 13, 14 (with memory adresses) followed by the new copied one.

Before i was getting segfault 11 but now it runs but is at the same memory addresses.

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;

}

}

网友答案:

first thing you do in your copy constructor is corrupting original list. n is list you are copying from and generally should not be modified, that is why usually copy constructors get const Type& as input argument.

you have to do something like

DLL::DLL(DLL& n) {
    int i = 0
    Node* temp = n.headPtr;
    while(temp != NULL){
        temp = temp->succ;
        insert(temp->ssn, temp->name, i++);
    }   
}
相关阅读:
Top