c++list容器用类模拟实现:迭代器遍历数据(含++、*、=运算符的重载)
作者:野牛程序员:2024-01-03 15:15:14 C++阅读 2673
c++list容器用类模拟实现:迭代器遍历数据(含++、*、=运算符的重载)
#include <iostream>
template <typename T>
class MyList {
private:
struct Node {
T data;
Node* next;
Node(const T& value) : data(value), next(nullptr) {}
};
Node* head;
public:
// 定义迭代器类
class Iterator {
private:
Node* current;
public:
Iterator(Node* node) : current(node) {}
// 重载前置++运算符
Iterator& operator++() {
if (current) {
current = current->next;
}
return *this;
}
// 重载后置++运算符
Iterator operator++(int) {
Iterator temp = *this;
++(*this);
return temp;
}
// 重载*运算符
T& operator*() {
return current->data;
}
// 重载==运算符
bool operator==(const Iterator& other) const {
return current == other.current;
}
// 重载!=运算符
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
};
MyList() : head(nullptr) {}
~MyList() {
while (head) {
Node* temp = head;
head = head->next;
delete temp;
}
}
void push_back(const T& value) {
Node* newNode = new Node(value);
if (!head) {
head = newNode;
} else {
Node* current = head;
while (current->next) {
current = current->next;
}
current->next = newNode;
}
}
// 获取链表头部的迭代器
Iterator begin() {
return Iterator(head);
}
// 获取链表尾部的迭代器
Iterator end() {
return Iterator(nullptr);
}
// 其他成员函数可以根据需要进行添加
};
int main() {
MyList<int> myList;
myList.push_back(10);
myList.push_back(20);
myList.push_back(30);
// 使用迭代器遍历数据
for (MyList<int>::Iterator it = myList.begin(); it != myList.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

