c++怎么实现单链表类
时间: 2024-09-24 19:17:17 浏览: 50
本函数完成一个单链表的逆置。-东南大学C++何洁月
在C++中实现单链表通常会涉及到节点(Node)结构、头结点(head)和一些基本操作,如插入、删除和遍历等。下面是一个简单的单链表类(LinkedList)的实现示例:
```cpp
#include <iostream>
// 定义链表节点结构
class Node {
public:
int data; // 节点数据
Node* next; // 指向下一个节点的指针
// 构造函数
Node(int value) : data(value), next(nullptr) {}
};
// 链表类
class LinkedList {
private:
Node* head; // 头结点指针
public:
// 构造函数,初始化空链表
LinkedList() : head(nullptr) {}
// 插入元素到链表末尾
void insert(int value) {
Node* newNode = new Node(value);
if (head == nullptr) {
head = newNode;
} else {
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
}
}
// 删除指定值的节点
void remove(int value) {
if (head == nullptr) return;
if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* current = head;
while (current->next != nullptr && current->next->data != value) {
current = current->next;
}
if (current->next != nullptr) {
Node* temp = current->next;
current->next = current->next->next;
delete temp;
}
}
// 打印链表
void printList() {
Node* temp = head;
while (temp != nullptr) {
std::cout << temp->data << " ";
temp = temp->next;
}
std::cout << "\n";
}
};
// 示例
int main() {
LinkedList list;
list.insert(10);
list.insert(20);
list.insert(30);
std::cout << "Original List:\n";
list.printList();
list.remove(20);
std::cout << "After removing 20:\n";
list.printList();
return 0;
}
```
阅读全文