sdd
Alexmegawin
c_cpp
2 years ago
2.8 kB
5
Indexable
#include <iostream> using namespace std; class List { private: class Node { friend class List; friend class Iterator; public: Node(int value) { this->value = value; this->next_node = nullptr; } Node(int value, Node* next_node) { this->value = value; this->next_node = next_node; } private: int value; Node* next_node; }; public: class Iterator { public: Iterator(Node* current, List* list) { this->current = current; this->list = list; } private: List* list; Node* current; public: Node* getNextNode() { return current->next_node; } void setNextNode(Node* node) { current->next_node = node; } int getValue() { return current->value; } void goNext() { current = current->next_node; } }; public: List() { head = nullptr; lenght = 0; } private: Node* head; int lenght; public: Iterator begin() { Iterator iterator(head, this); return iterator; } void addToHead(int value) { Node* new_head = new Node(value, head); head = new_head; lenght++; } void addNode(int value, Iterator iterator) { Node* new_nod = new Node(value, iterator.getNextNode()); iterator.setNextNode(new_nod); lenght++; } bool deleteFromHead(int* result) { if (lenght == 0) { return false; } Node* pre_head = head; head = head->next_node; *result = pre_head->value; delete pre_head; lenght--; return true; } void printList() { Node* current = head; while (current != nullptr) { cout << current->value << " "; current = current->next_node; } } }; int main() { List list; for (int i = 0; i < 5; i++) { list.addToHead(i); } list.printList(); cout << endl; List::Iterator iterator = list.begin(); cout << iterator.getValue() << " "; list.addNode(100, iterator); cout << iterator.getValue() << " "; iterator.goNext(); cout << iterator.getValue() << " "; /*for (int i = 0; i < 5; i++) { cout << iterator.getValue() << " "; iterator.goNext(); }*/ return 0; }
Editor is loading...