要创建和使用一个C++链表类,你可以按照以下步骤进行:
class Node {
public:
int data;
Node* next;
};
class LinkedList {
private:
Node* head;
public:
LinkedList() {
head = nullptr; // 初始化链表为空
}
// 在链表末尾插入一个节点
void insert(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = nullptr;
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* previous = head;
Node* current = head->next;
while (current != nullptr) {
if (current->data == value) {
previous->next = current->next;
delete current;
return;
}
previous = current;
current = current->next;
}
}
// 打印链表中的所有节点值
void print() {
Node* current = head;
while (current != nullptr) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
};
int main() {
LinkedList list;
list.insert(1);
list.insert(2);
list.insert(3);
list.print(); // 输出:1 2 3
list.remove(2);
list.print(); // 输出:1 3
return 0;
}
这是一个简单的链表类的例子,你可以根据你的需求进行修改和扩展。