如何为链表创建一个复制构造函数



我完成了这个程序中的每一个函数,我基本上了解了这些概念,但链表的复制构造函数让我很困惑。我看了其他关于这个问题的答案,但我不知道如何将其应用于我的情况。

我有三个文件,一个test.cpp包含main((,一个IntList.cpp和一个IntList.h。

test.cpp和IntList.h是由我的教授提供的,所以可以肯定地假设没有错误。我只需要写IntList.cpp.

#include <iostream>
#include <cstdlib>
#include "IntList.h"

using namespace std;
IntList::IntList()
{
head = NULL;
}
IntList::IntList(const IntList &)
{
???
}

这是IntList.h。如果你需要test.cpp或IntList.cpp中的其他函数,请告诉我。

// Specification file for the IntList class
#ifndef INTLIST_H
#define INTLIST_H
class IntList
{
private:
// Declare a structure for the list
struct ListNode
{
int value;
struct ListNode *next;
};
ListNode *head;   // List head pointer
public:
// Constructor
IntList();
// Copy constructor
IntList(const IntList &);
// Destructor
~IntList();
// List operations
void appendNode(int val);
void removeByVal(int val);
void displayList();
void insertByPos(int val, int pos);
void removeByPos(int pos);
int search(int val);
};
#endif /* INTLIST_H_ */

编辑:

我正在阅读你们的评论,但它只是不适合我。

我试图重写代码,但仍然没有意义。这是我的尝试,我觉得我只是不明白这应该是什么样子。

IntList::IntList(const IntList &list) // maybe I name it list so I can refer to list.head?
{
ListNode *nodePtr;
nodePtr = list.head;
if (nodePtr == NULL) // If the head of list is empty then theres no list to copy
{ 
return;
}
while (nodePtr->next != 0) // Trying to iterate through the link
{
nodePtr = nodePtr->next;
}
ListNode *newNode;   
nodePtr->next = newNode; 
// ??? Confused again. 

这是我的displayList((函数

void IntList::displayList()
{
ListNode *nodePtr;
nodePtr = head;
while (nodePtr != NULL)
{
cout << nodePtr->value << endl;
nodePtr = nodePtr->next;
}
}

这是我的appendNode((。

void IntList::appendNode(int val)
{
ListNode *newNode;
ListNode *nodePtr;
newNode = new ListNode;
newNode->value = val;
newNode->next = NULL;

if (!head)
{
head = newNode;
}
else
{
nodePtr = head;
while (nodePtr->next != 0)
{
nodePtr = nodePtr->next;
}
nodePtr->next = newNode;
}
}

这些对我来说很有意义,我很快就完成了。我不知道如何将这些想法实现到复制构造函数中。你们能帮我弄清楚我没有得到什么吗?

这是

IntList::IntList( const IntList &list ) : head( nullptr )
{
ListNode **new_node = &this->head;
for ( auto current = list.head; current != nullptr; current = current->next )
{
*new_node = new ListNode { current->value, nullptr };
new_node = &( *new_node )->next; 
}         
}

如果你很难理解如何处理指向指针的指针,那么我可以建议另一个不使用指向指针的构造函数定义。

IntList::IntList( const IntList &list ) : head( nullptr )
{
if ( list.head != nullptr )
{
this->head = new ListNode { list.head->value, nullptr };
for ( auto new_node = this->head, current = list.head->next;
current != nullptr;
new_node = new_node->next, current = current->next )
{
new_node->next = new ListNode { current->value, nullptr };
}             
}
}

最新更新