C++ 链表拷贝: 深拷贝实现详解
C++ 中的链表可以通过拷贝构造函数和赋值运算符进行深拷贝。
深拷贝意味着创建新的节点并复制原始链表中的所有数据。这确保了原始链表和副本之间没有相互依赖,修改副本不会影响原始链表。
拷贝构造函数:
class LinkedList {
public:
// 节点类
class Node {
public:
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
// 拷贝构造函数
LinkedList(const LinkedList& other) : head(nullptr) {
if (other.head == nullptr) {
return;
}
head = new Node(other.head->data);
Node* p = head;
Node* q = other.head->next;
while (q != nullptr) {
p->next = new Node(q->data);
p = p->next;
q = q->next;
}
}
// ...
private:
Node* head;
};
赋值运算符:
class LinkedList {
public:
// 节点类
class Node {
public:
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
// 拷贝构造函数
LinkedList(const LinkedList& other) : head(nullptr) {
if (other.head == nullptr) {
return;
}
head = new Node(other.head->data);
Node* p = head;
Node* q = other.head->next;
while (q != nullptr) {
p->next = new Node(q->data);
p = p->next;
q = q->next;
}
}
// 赋值运算符
LinkedList& operator=(const LinkedList& other) {
if (this == &other) {
return *this;
}
// 释放原有链表的内存
Node* p = head;
while (p != nullptr) {
Node* q = p;
p = p->next;
delete q;
}
head = nullptr;
// 拷贝新的链表
if (other.head == nullptr) {
return *this;
}
head = new Node(other.head->data);
p = head;
Node* q = other.head->next;
while (q != nullptr) {
p->next = new Node(q->data);
p = p->next;
q = q->next;
}
return *this;
}
private:
Node* head;
};
注意:
- 拷贝构造函数和赋值运算符都需要处理空链表的情况,以避免空指针异常。
- 赋值运算符需要释放原有链表的内存,以防止内存泄漏。
通过这些实现,我们可以确保在复制链表时,创建的是独立的副本,而不是简单的引用。
原文地址: https://www.cveoy.top/t/topic/n1dw 著作权归作者所有。请勿转载和采集!