How can classes be used to implement a linked list in C++?
To implement a linked list using classes, first define a node class to represent the nodes of the list, and then define a linked list class to manipulate these nodes.
Here is an example of implementing a linked list using a class.
#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 append(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 insert(int value, int index) {
if (index < 0) {
std::cout << "Invalid index!" << std::endl;
return;
}
Node* newNode = new Node(value);
if (index == 0) {
newNode->next = head;
head = newNode;
} else {
Node* current = head;
for (int i = 0; i < index - 1; i++) {
if (current == nullptr) {
std::cout << "Invalid index!" << std::endl;
return;
}
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
// 删除链表指定位置的节点
void remove(int index) {
if (index < 0) {
std::cout << "Invalid index!" << std::endl;
return;
}
if (index == 0) {
Node* temp = head;
head = head->next;
delete temp;
} else {
Node* current = head;
for (int i = 0; i < index - 1; i++) {
if (current == nullptr || current->next == nullptr) {
std::cout << "Invalid index!" << std::endl;
return;
}
current = current->next;
}
Node* temp = current->next;
current->next = temp->next;
delete temp;
}
}
// 打印链表中的所有节点值
void print() {
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
};
int main() {
LinkedList myList;
myList.append(1);
myList.append(2);
myList.append(3);
myList.insert(4, 1);
myList.print(); // 输出:1 4 2 3
myList.remove(2);
myList.print(); // 输出:1 4 3
return 0;
}
In the example above, we first define a node class Node, which includes an integer data member and a pointer pointing to the next node.
Next, we defined a LinkedList class, which includes a pointer “head” pointing to the head of the linked list. This class implements several basic operations such as inserting a node at the tail of the list, inserting a node at a specified position, deleting a node at a specified position, and printing all nodes in the list.
In the main function, we instantiated a linked list object called myList and performed some insertions, deletions, and printing operations, before finally destroying the linked list object.
When you run the example code above, the following result will be displayed:
1 4 2 3
1 4 3
This indicates that the linked list implemented using classes can function properly.