我一直在尝试为双向链表类实现一个复制构造函数,它创建一个深层副本。我一直在遇到这个问题 push_back()函数尝试操作的头部和尾部是未定义的或nullptr。如果有人对双向链表有任何经验,请随时提供帮助。
我的复制构造函数:
//copy constructor
DoubleLinkedList::DoubleLinkedList(const DoubleLinkedList& dll)
{
copyList(dll);
}
我的copyList函数定义:
void DoubleLinkedList::copyList(const DoubleLinkedList& listToBeCopied)
{
if (listToBeCopied.head == head) //checks to make sure that the list that is being copied isn't the same as the one it is copying to
{
return;
}
listToBeCopied.resetIterator(); //sets the iterator to head
while (listToBeCopied.hasMore()) //continues to run as long as iterator is not equal to a nullptr (tail->next).
{
push_back((listToBeCopied.next())); //takes the data from the iterator and pushes it to the back of the list.
}
}
我的push_back()函数定义:
// insert str at back of list
void DoubleLinkedList::push_back(const AMString& str)
{
Node *temp = new Node(str);
if (head == nullptr)
{
head = tail = temp;
head->prev = nullptr;
//cout << "\"" << str << "\" was added to the front and back (push_back).\n\n";
}
else
{
temp->prev = tail;
tail->next = temp;
tail = temp;
//cout << "\"" << str << "\" was added the back.\n\n";
}
count++;
}