我正在编写自己的链表类(用于教育目的),如下:
我的代码
#include <iostream>
using namespace std;
#define PRINT(x) #x << " = " << x << " "
struct ListNode {
int val;
ListNode* next = nullptr;
ListNode(int x) : val(x), next(nullptr) {}
};
class LinkedList {
private:
ListNode* _head;
unsigned long long int _size;
public:
LinkedList() :_head(nullptr), _size(0) {}
LinkedList(ListNode* _h) :_head(_h), _size(0) {
ListNode* node = _head;
while (node != nullptr) {
_size++;
node = node->next;
}
}
// Copy constructor
LinkedList(const LinkedList& obj) {
ListNode* node = obj._head;
while (node != nullptr) {
this->add(node->val);
node = node->next;
}
}
~LinkedList() {
while (_head != nullptr) {
remove();
}
}
void add(const int& value) {
ListNode* node = new ListNode(value);
node->next = _head;
_head = node;
_size++;
}
int remove() {
int v = _head->val;
ListNode* node = _head;
_head = _head->next;
delete node;
_size--;
return v;
}
void print() {
if (size() == 0) {
cout << "List is empty" << endl;
return;
}
ListNode* node = _head;
while (node->next != nullptr) {
cout << node->val << " -> ";
node = node->next;
}
cout << node->val << endl;
}
unsigned long long int size() { return _size; }
ListNode* head() { return _head; }
};
int main() {
LinkedList L;
L.add(4);
L.add(3);
L.add(2);
L.add(1);
L.print();
LinkedList L2(L);
return 0;
}
问题是,当我运行此代码时,我收到此错误:对象0x7fff5b8beb80的错误:正在释放的指针未分配
我不明白为什么。复制构造函数之外的逻辑很简单:我迭代要复制的列表,即 obj
,然后向 this
列表添加一个新元素,即我要复制到的列表。由于我的 add()
函数使用 new
创建了一个新元素,因此我看不到我的两个列表在哪里共享一个我试图删除两次的元素在析构函数中。我究竟做错了什么?
最佳答案
您忘记在复制构造函数中初始化您的_head
:
// Copy constructor
LinkedList(const LinkedList &obj) {
_head = NULL; // <- Add This
ListNode *node = obj._head;
while (node != nullptr) {
this -> add(node -> val);
node = node -> next;
}
}
关于c++ - 链表的复制构造函数会导致内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60653023/