定义包含数据和指针的节点结构,2. 实现链表类封装,3. 提供头尾插入、删除、查找和打印功能,4. 通过示例验证操作正确性。

在C++中手动实现一个链表,核心是定义节点结构和管理节点之间的连接。下面一步步带你实现一个基础的单向链表,包含插入、删除、遍历等常用操作。
定义链表节点结构
链表由一系列节点组成,每个节点包含数据和指向下一个节点的指针。
struct ListNode { int data; // 存储的数据(以int为例) ListNode* next; // 指向下一个节点的指针// 构造函数,方便创建节点ListNode(int val) : data(val), next(nullptr) {}
};
实现链表类
封装链表操作到一个类中,便于管理。我们从最简单的单向链表开始。
立即学习“C++免费学习笔记(深入)”;
class LinkedList {private: ListNode* head; // 头指针,指向第一个节点public:// 构造函数LinkedList() : head(nullptr) {}
// 析构函数:释放所有节点内存~LinkedList() { while (head != nullptr) { ListNode* temp = head; head = head->next; delete temp; }}// 在链表头部插入新节点void insertAtHead(int val) { ListNode* newNode = new ListNode(val); newNode->next = head; head = newNode;}// 在链表尾部插入新节点void insertAtTail(int val) { ListNode* newNode = new ListNode(val); if (head == nullptr) { head = newNode; return; } ListNode* current = head; while (current->next != nullptr) { current = current->next; } current->next = newNode;}// 删除第一个值为val的节点bool remove(int val) { if (head == nullptr) return false; if (head->data == val) { ListNode* temp = head; head = head->next; delete temp; return true; } ListNode* current = head; while (current->next != nullptr && current->next->data != val) { current = current->next; } if (current->next != nullptr) { ListNode* temp = current->next; current->next = current->next->next; delete temp; return true; } return false; // 未找到}// 查找某个值是否存在bool find(int val) { ListNode* current = head; while (current != nullptr) { if (current->data == val) return true; current = current->next; } return false;}// 打印链表所有元素void print() { ListNode* current = head; while (current != nullptr) { std::cout <data < "; current = current->next; } std::cout << "nullptr" << std::endl;}
};
使用示例
下面是一个简单的测试代码,展示如何使用上面实现的链表。
#include using namespace std;int main() {LinkedList list;
list.insertAtTail(10);list.insertAtTail(20);list.insertAtHead(5);list.print(); // 输出: 5 -> 10 -> 20 -> nullptrlist.remove(10);list.print(); // 输出: 5 -> 20 -> nullptrcout << "Contains 20? " << (list.find(20) ? "Yes" : "No") << endl;return 0;
}
基本上就这些。这个链表实现了基本的增删查功能,适合学习理解指针和动态内存管理。后续可以扩展双向链表、循环链表,或添加更多操作如插入到指定位置、反转链表等。
以上就是c++++怎么实现一个链表_c++手动实现链表结构教程的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1479144.html
微信扫一扫
支付宝扫一扫