首先定义链表节点结构,包含数据域和指向下一节点的指针;接着封装链表类,管理头指针并提供插入、删除、查找、遍历等操作;构造函数初始化头指针为空,析构函数释放所有节点内存;插入支持头插和尾插,删除按值移除节点并释放内存,查找遍历判断是否存在目标值,显示函数输出链表内容;使用示例验证功能正确性,注意处理空链表、删头节点等边界情况,避免野指针与内存泄漏。

实现一个单向链表,核心是定义节点结构和操作接口。C++中可以通过类封装数据和操作,让链表更易用、安全。
每个节点包含数据和指向下一个节点的指针。
struct或class定义节点,通常struct更简洁。示例:
struct ListNode {
int data;
ListNode* next;
ListNode(int val) : data(val), next(nullptr) {}
};用类管理链表头指针和常用操作,比如插入、删除、查找、遍历等。
立即学习“C++免费学习笔记(深入)”;
简单实现:
class SinglyLinkedList {
private:
ListNode* head;
<p>public:
SinglyLinkedList() : head(nullptr) {}</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">~SinglyLinkedList() {
while (head) {
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) {
head = newNode;
return;
}
ListNode* current = head;
while (current->next) {
current = current->next;
}
current->next = newNode;
}
bool remove(int val) {
if (!head) return false;
if (head->data == val) {
ListNode* temp = head;
head = head->next;
delete temp;
return true;
}
ListNode* current = head;
while (current->next && current->next->data != val) {
current = current->next;
}
if (current->next) {
ListNode* temp = current->next;
current->next = current->next->next;
delete temp;
return true;
}
return false;
}
bool find(int val) {
ListNode* current = head;
while (current) {
if (current->data == val) return true;
current = current->next;
}
return false;
}
void display() {
ListNode* current = head;
while (current) {
std::cout << current->data << " -> ";
current = current->next;
}
std::cout << "nullptr" << std::endl;
}};
在main函数中创建链表对象并调用方法测试功能。
int main() {
SinglyLinkedList list;
list.insertAtHead(10);
list.insertAtTail(20);
list.insertAtTail(30);
list.display(); // 输出: 10 -> 20 -> 30 -> nullptr
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">list.remove(20);
list.display(); // 输出: 10 -> 30 -> nullptr
std::cout << (list.find(30) ? "Found" : "Not found") << std::endl;
return 0;}
基本上就这些。掌握节点定义、指针操作和内存管理,就能写出一个稳定可用的单向链表。注意边界情况,比如空链表、删头节点等,避免野指针和内存泄漏。
以上就是c++++怎么实现一个单向链表_c++单向链表结构实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号