要創建和使用一個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;
}
這是一個簡單的鏈表類的例子,你可以根據你的需求進行修改和擴展。