以下是具有节点结构的类,链表副本构造函数和我的主文件。它将打印第一个列表中的数字,并仅将第一个数字(15)复制到第二个列表中。它调用两个列表的析构函数,程序正常关闭。无论我尝试多么努力,我都无法弄清楚这个拷贝构造函数,它真的开始打扰我了。复制构造函数不适用于链接列表?
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <iostream>
using namespace std;
// Declare a class for the list
class LinkedList
{
private:
// Declaring a structure for the list
struct ListNode
{
// Integer value in the node and pointer to the next node
int value = NULL;
struct ListNode* next = nullptr;
};
// List head pointer
ListNode* head = nullptr;
public:
// Constructor
LinkedList() { head = nullptr; };
// Copy constructor
LinkedList(const LinkedList &);
// Destructor
virtual ~LinkedList();
// Linked list operations
void appendNode(int);
void insertNode(int);
void deleteNode(int);
void printList() const;
void reverseList() const;
int searchList(const int) const;
};
#endif // LINKEDLIST_H
LinkedList::LinkedList(const LinkedList& listObj)
{
ListNode* newNode = nullptr; // Create new node
ListNode* copyPtr = nullptr; // Point to original object
copyPtr = listObj.head;
newNode = new ListNode;
this->head = newNode;
head->value = copyPtr->value;
copyPtr = copyPtr->next;
while(!copyPtr)
{
newNode->next = new ListNode;
newNode = newNode->next;
newNode->value = copyPtr->value;
copyPtr = copyPtr->next;
}
}
#include "LinkedList.h"
#include <iostream>
using namespace std;
int main()
{
LinkedList list1;
list1.appendNode(15);
list1.appendNode(20);
list1.appendNode(25);
list1.printList();
LinkedList list2 = list1;
list2.printList();
return 0;
}
为什么我会在while循环结束时执行'newNode-> next = nullptr'? – bigZigZag