1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| #include <iostream>
template<typename T> struct Node { T data; Node* prev; Node* next; Node(const T& val) : data(val), prev(nullptr), next(nullptr) {} };
template<typename T> class ListIterator { public: ListIterator(Node<T>* node) : node(node) {}
T& operator*() const { return node->data; }
ListIterator& operator++() { node = node->next; return *this; }
ListIterator operator++(int) { ListIterator temp = *this; ++(*this); return temp; } bool operator==(const ListIterator& other) const { return node == other.node; }
bool operator!=(const ListIterator& other) const { return !(*this == other); }
private: Node<T>* node; };
template<typename T> class List { public: using iterator = ListIterator<T>;
List() : head(nullptr), tail(nullptr) {}
void push_back(const T& value) { Node<T>* newNode = new Node<T>(value); if (!tail) { head = tail = newNode; } else { tail->next = newNode; newNode->prev = tail; tail = newNode; } } iterator begin() { return iterator(head); } iterator end() { return iterator(nullptr); }
~List() { while (head) { Node<T>* temp = head; head = head->next; delete temp; } }
private: Node<T>* head; Node<T>* tail; };
int main() { List<int> lst; lst.push_back(1); lst.push_back(2); lst.push_back(3);
for (const auto& x : lst) { std::cout << x << " "; }
return 0; }
|