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/e13X 著作权归作者所有。请勿转载和采集!