如何清空C++自定义Linked List对象?解决赋值nullptr报错问题
问题:如何清空自定义C++链表?
你实现了如下的C++链表代码(包含Node类与List类,支持insert、print方法):
#include <string> #include <iostream> using namespace std; class Node { public: string name; int age; Node *next; Node(string name, int age) { this->name = name; this->age = age; this->next = nullptr; } }; class List { private: Node *head; int size; public: List() { this->head = nullptr; this->size = 0; } void insert(string name, int age) { Node *nodenew = new Node(name, age); nodenew->next = nullptr; if (this->head == nullptr) { this->head = nodenew; } else { Node *auxi = this->head; while (auxi->next != nullptr) { auxi = auxi->next; } auxi->next = nodenew; } this->size = this->size + 1; } void print() { if (this->head == nullptr) { cout << "List is empty"<<endl; } Node *auxi = this->head; cout<<to_string(this->size)+" users in the linked list"<<endl; while (auxi != nullptr) { cout << auxi->name << ", " << auxi->age << endl; auxi = auxi->next; } } }; int main() { List linkedList; linkedList.insert("David", 56); linkedList.insert("Susan", 25); linkedList.insert("Kim", 41); linkedList.insert("Charles", 23); linkedList.insert("Bob", 20); linkedList.insert("James", 75); linkedList.insert("Carl", 36); linkedList.insert("Andy", 78); linkedList.print(); return 0; }
尝试用linkedList = nullptr;清空链表时,编译器报错:no operator "=" matches these operands,请问正确的清空方法是什么?
解决方案
错误原因
linkedList是List类型的对象实例,并非指针类型,因此不能直接给它赋值nullptr。C++中只有指针或智能指针才能接受nullptr赋值。
正确实现:添加clear成员方法
需要给List类添加一个clear方法,负责遍历链表释放所有节点的堆内存,同时重置链表的head指针和size属性。
修改后的List类代码如下(新增clear方法):
class List { private: Node *head; int size; public: List() { this->head = nullptr; this->size = 0; } // 新增clear方法 void clear() { Node *current = head; while (current != nullptr) { Node *nextNode = current->next; // 先保存下一个节点的地址 delete current; // 释放当前节点内存 current = nextNode; // 移动到下一个节点 } head = nullptr; // 重置头指针 size = 0; // 重置大小 } void insert(string name, int age) { // 原insert方法代码不变 Node *nodenew = new Node(name, age); nodenew->next = nullptr; if (this->head == nullptr) { this->head = nodenew; } else { Node *auxi = this->head; while (auxi->next != nullptr) { auxi = auxi->next; } auxi->next = nodenew; } this->size = this->size + 1; } void print() { // 原print方法代码不变 if (this->head == nullptr) { cout << "List is empty"<<endl; } Node *auxi = this->head; cout<<to_string(this->size)+" users in the linked list"<<endl; while (auxi != nullptr) { cout << auxi->name << ", " << auxi->age << endl; auxi = auxi->next; } } };
使用方式
在main函数中直接调用clear方法即可清空链表:
int main() { List linkedList; linkedList.insert("David", 56); linkedList.insert("Susan", 25); linkedList.print(); // 清空链表 linkedList.clear(); linkedList.print(); // 此时会输出"List is empty"和"0 users in the linked list" return 0; }
额外建议
为了避免内存泄漏,建议同时给List类添加析构函数,在对象销毁时自动调用clear方法:
~List() { clear(); }
这样当List对象生命周期结束时(比如main函数结束),会自动释放所有节点的内存,无需手动调用clear。
内容的提问来源于stack exchange,提问作者narocac
相关产品推荐
相关产品推荐

