C++のリストクラスの作成と使用方法は?
C++のリストクラスを作成して使用するには、以下の手順に従うことができます。
- ノードクラスを作成します:ノードクラスは、通常、リスト内の1つのノードを表し、データメンバーと次のノードを指すポインターを含んでいます。
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;
}
これは簡単なリストクラスの例ですが、必要に応じて変更や拡張を行うことができます。