有没有办法在c++中使用类和对象而不是指针来实现链表?
我想使用面向对象的编程方法。
是的,可以使用类和对象而不是原始指针在 C++ 中实现链表。在面向对象的方法中,您可以为链表本身定义一个类,并为链表的节点定义另一个类。这是一个简单的例子:
#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 display() {
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
~LinkedList() {
Node* current = head;
while (current != nullptr) {
Node* next = current->next;
delete current;
current = next;
}
head = nullptr;
}
};
int main() {
LinkedList myList;
myList.append(1);
myList.append(2);
myList.append(3);
std::cout << "Linked List: ";
myList.display();
return 0;
}