我已经完成了该程序中的每个功能,并且大部分都了解了概念,但是链表的副本构造函数让我很头疼。我正在查看有关此问题的其他答案,但我不知道如何将其应用于我的情况。
我有三个文件,一个包含main()的test.cpp,一个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 ) : 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;
}
}